Juliver Galleto
Juliver Galleto

Reputation: 9047

add json item to a existing json array

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

Answers (2)

A l w a y s S u n n y
A l w a y s S u n n y

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

PJAutomator
PJAutomator

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

Related Questions