0

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?

Juliver Galleto
  • 8,831
  • 27
  • 86
  • 164
  • 7
    It is because it is not an array . it should be $arr = [{},{}] – amrender singh Aug 30 '18 at 16:36
  • 2
    It is not even a valid object in JS – Arup Rakshit Aug 30 '18 at 16:36
  • 1
    that's because $arr is an invalid object, try `var $arr = [ { name : "name1", age : 12 },{ name : "name2", age : 12 } ];` – Madhan Varadhodiyil Aug 30 '18 at 16:36
  • 4
    Above all, this isn’t JSON. [There’s no such thing as a “JSON Object”](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). Neither “JSON object” nor “JSON array” nor “JSON object array” make any sense. Your question doesn’t contain any JSON, just objects and invalid syntax. – Sebastian Simon Aug 30 '18 at 16:38
  • _"JSON (JavaScript Object Notation) is a textual data interchange format and language-independent."_ -> [javascript - What is the difference between JSON and Object Literal Notation? - Stack Overflow](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – Andreas Aug 30 '18 at 16:39

2 Answers2

1

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 } ]
PJAutomator
  • 344
  • 3
  • 12
1

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);
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103