Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push an array inside another array element as a new property in JavaScript? [duplicate]

So, For instance, I have the following array

var sections = [{ name: 'apple', count: 20 },
                 { name: 'banana', count: 80 },
                 { name: 'oranges', count: 10 }]

Now, if I want to add more items, then I can do

sections.push({ name: 'mango', count: '32' });

which will add the new array to sections.

Now, suppose, I have another array that shows where the fruit came from and how many.

var country = [{ country: 'usa', count: 5 },
               { country: 'brazil', count: 27 }]

So, I want to add this new country array to the third element of sections with a new prop called country as the following.

var sections = [{ name: 'apple', count: 20 },
                { name: 'banana', count: 80 },
                { name: 'oranges', count: 10,
                  country: [{ country: 'usa', count: 5 },
                            { country: 'brazil', count: 27 }]
                }]

How can I do this? I tried push, splice but couldn't figure it out at all.

I also tried sections[3].push.apply(country).. and many other things that I can't recall anymore. Either I received an error or just didn't push the array as I wanted to.

like image 332
user1828605 Avatar asked Sep 26 '22 06:09

user1828605


2 Answers

You could try something like this:

sections[2].country =  country;

Here, writing sections[2] we peek a reference to the third item of the sections. Then we define a property called country and we assign to it the value we want.

Why push didn't work?

The push is an array method, that gives you the ability to push an element at the end of an array. If you try to make use of push on sections[2] will not work, since sections[2] is not an array. The same holds for the splice, it's an array method.

like image 164
Christos Avatar answered Sep 29 '22 00:09

Christos


push is for adding to an array, not for adding properties to an object. For a property, just assign the property name.

sections[2].country = country;

If the property already existed and you wanted to add to it, you would use push as follows:

section[2].country.push({country: 'venezuela', count: 20});

And don't forget that array indexes start at 0, so the third element is [2].

like image 37
Barmar Avatar answered Sep 29 '22 00:09

Barmar