How to add Indice to an array

Asked

Viewed 1,628 times

1

I am creating an Array in Javascript in the following format:

series = [{
                name: 'Tokyo',
                data: [7.0, 6.9, 9.5]
            }, {
                name: 'New York',
                data: [-0.2, 0.8, 5.7]
            }]

But in some cases, I have to add new values data:

data: [-0.2, 0.8, 5.7, 2.7, 8.9, ...]

someone knows how to do this?

  • 1

    You want to enter more values in one of these arrays data existing, or insert a new city into the outermost array?

  • Insert more values into the array data

  • Which one? In your example there are 2.

  • whatever, I want to know how you do to insert more values in any one..

  • @Thiago if your question is more complete will have more complete and exact answers. How do you want to change the array? One by one? or as a consequence of another code?

2 answers

4

You can add new values using the .push():

series[1].data.push(5)
series[1].data
2014-08-01 13:00:41.524[-0.2, 0.8, 5.7, 5]

4


You can use the method push() javascript to do what you want.

For example, taking your array:

series = [{
    name: 'Tokyo',
    data: [7.0, 6.9, 9.5]
}, {
    name: 'New York',
    data: [-0.2, 0.8, 5.7]
}]

If you want to add an element to each data, you walk the array in one .each() and add what you want. Something like:

    $.each(series, function (index, itemData) {
       itemData.data.push(12);
    });

I leave here Jsfiddle to see. In this example I am adding 12 in the data

  • .push() wouldn’t that be a Javascript method? Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

  • Yes I went to check and it’s javascript. Thanks for your attention

Browser other questions tagged

You are not signed in. Login or sign up in order to post.