Vandervidi
Vandervidi

Reputation: 692

Pushing data into an array in a Json object

I need to push an an object into an array in in a Json file. To make it simple lets say that my Json looks like this:

var JsonObj = {
"elements" : []
}

I tried Push() method but it didnt work. tried also to assign to JsonObj.elements[0]= ... it also fails. How can i make it work?

Upvotes: 0

Views: 767

Answers (2)

Legendary
Legendary

Reputation: 2242

Try that way, it has to work:

JsonObj.elements.push(1);

FIddle: https://jsfiddle.net/29qa4bfw/1/

Upvotes: 1

Fourat
Fourat

Reputation: 2447

This is basic Javascript. nothing to do with Json or jQuery:

var jsonObj = {
"elements" : []
};

jsonObj.elements.push(1);
jsonObj.elements.push(1.5);
jsonObj.elements.push("some text");
jsonObj.elements.push({element: "some element"});

Here's a jsbin to fool around with: http://jsbin.com/hajale/2/edit

Upvotes: 0

Related Questions