7

I have a JSON variable defined as:

var myCollection = {
 "data": [
 { "name":"Joe", "id":"1" },
 { "name":"Bill", "id":"2" },
 { "name":"Dave", "id":"3" }
 ]
};

I have a JavaScript function that is responsible for adding items to the data element in myCollection. However, I'm not sure how to add a name/id pair to the collection via JavaScript. Can someone show me how to add to a JSON collection via JavaScript?

Thank you!

asked May 27, 2010 at 13:27
1
  • 2
    FYI you can use numeric data in JSON without quoting it. So { "name":"Joe", "id":1 } is still valid JSON. Commented May 27, 2010 at 14:32

1 Answer 1

25

You can simply call the push method on the "data" array:

myCollection.data.push( { "name":"Jim", "id":"4" } );
answered May 27, 2010 at 13:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.