BobbyJones BobbyJones -5 years ago 102
Javascript Question

Pushing a value to an array of objects

I can't seem to figure out as to why I am unable to append a value to my array below? Is there a special syntax to follow or something when constructing an array like in the method used below?

var arr = {
"fruits": ['apple','banana','orange']

arr.push({ "fruits":"testing123"}) <-- This line fails


Answer Source

Your array defintion is all wrong. Assuming you want arr to be an object that has an array under fruits and then push another value inside fruits, use the following:

var arr = {fruits: ['apple','banana','orange']};
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download