Reputation: 9047
I have this json
var $arr = { { name : "name1", age : 12 },{ name : "name2", age : 12 } };
how can I add/append an item to the existing json array? tried
$arr.push({ name : "name3", age : 14 });
but it gives me,
$arr.push is not a function
Any ideas, help please?
Upvotes: 0
Views: 806
Reputation: 38552
Just do it with proper array of objects
, here you've created an invalid syntax. Simply replace the first and last curly braces {}
to brackets []
and try your existing code again. More about array and objects
// see I've used brackets instead of curly braces
var $arr = [{name: "name1",age: 12}, {name: "name2",age: 12}];
$arr.push({name: "name3",age: 14});
console.log($arr);
Upvotes: 1
Reputation: 342
This is how it should be like for the push to happen. The $arr in your question is not a javascript array.
var $arr = [{ name: 'name1', age: 12 }, { name: 'name2', age: 12 }];
$arr.push({ name: 'name3', age: 14 });
console.log($arr);
Output:
[ { name: 'name1', age: 12 },
{ name: 'name2', age: 12 },
{ name: 'name3', age: 14 } ]
Upvotes: 1