HypeZ HypeZ - 6 months ago 18
Javascript Question

Adding elements to object

I need to populate a json file, now I have something like this:

{"element":{"id":10,"quantity":1}}


And I need to add another "element". My first step is putting that json in a Object type using
cart = JSON.parse
, now i need to add the new element.
I suppose I must use "cart.push" to add another element, i tried with

var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);


But I got error "Object has no method push" when I try to do element.push, and I think I'm doing something VERY wrong because I'm not telling the "element" anywhere.

How can I do that?

Edit: sorry to all I had a LOT of confusion in my head.

I tought I can get only object type when taking data from JSON.parse, but I get what I put in the JSON in the first place.

Putting array instead of object solved my problem, I used lot of suggestion got here too, thank you all!

Answer

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]"