BobbyJones BobbyJones - 5 months ago 8
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

alert(arr["fruits"])

Answer

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']};
arr.fruits.push("testing123");
alert(arr["fruits"]);