Adding elements to object

前端 未结 17 2187
有刺的猬
有刺的猬 2020-12-02 04:11

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

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

And I need to add another \"elemen

17条回答
  •  萌比男神i
    2020-12-02 04:27

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

提交回复
热议问题