javascriptjsonobject

Adding elements to an object


I need to populate a JSON file:

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

And I need to add another "element". My first step is putting that JSON in an Object type using cart = JSON.parse. Now I need to add the new element:

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

But I got:

Object has no method push

on element.push, I think because I'm not referencing the "element" anywhere. How can I do that?


Solution

  • 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}]"