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?

5
  • 7
    It is because it is not an array . it should be $arr = [{},{}] Commented Aug 30, 2018 at 16:36
  • 2
    It is not even a valid object in JS Commented Aug 30, 2018 at 16:36
  • 1
    that's because $arr is an invalid object, try var $arr = [ { name : "name1", age : 12 },{ name : "name2", age : 12 } ]; Commented Aug 30, 2018 at 16:36
  • 4
    Above all, this isn’t JSON. There’s no such thing as a “JSON Object”. 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. Commented Aug 30, 2018 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 Commented Aug 30, 2018 at 16:39

2 Answers 2

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 } ]
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.