5

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.

6
  • 2
    sections[2].country = country; Commented Nov 9, 2015 at 22:30
  • Really??!!!!. It's that easy? And I was trying all the other difficult ways in the world?? Gosh!!! Thanks Commented Nov 9, 2015 at 22:32
  • Does "another array" index positions correspond to sections array index positions ? Commented Nov 9, 2015 at 22:37
  • Not exactly sure what you mean, but the answers I got are all correct answers. Commented Nov 9, 2015 at 22:39
  • @user1828605 Yes . sections contains 3 items . Does "another array" contain 3 items corresponding to section items ? Commented Nov 9, 2015 at 22:43

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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].

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.