How to move an array inside another element of an array as a new property in JavaScript?

So, For example, 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 elements, then I can do

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

which will add a new array to the partitions.

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

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

So, I want to add this new array countryto the third element sectionswith a new name prop named by the country as follows.

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, splicebut could not figure it out at all.

I also tried sections [3] .push.apply (country) .. and many other things that I can no longer remember. Either I got an error, or simply did not push the array as I wanted.

+4
2

- :

sections[2].country =  country;

, sections[2], sections. , country, .

?

- , . push sections[2], , sections[2] . splice, .

+2

push , . .

sections[2].country = country;

, push :

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

, 0, [2].

+1

Source: https://habr.com/ru/post/1615131/


All Articles