Adding elements to object

前端 未结 17 2222
有刺的猬
有刺的猬 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条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 04:34

    If the cart has to be stored as an object and not array (Although I would recommend storing as an []) you can always change the structure to use the ID as the key:

    var element = { quantity: quantity };
    cart[id] = element;
    

    This allows you to add multiple items to the cart like so:

    cart["1"] = { quantity: 5};
    cart["2"] = { quantity: 10};
    
    // Cart is now:
    // { "1": { quantity: 5 }, "2": { quantity: 10 } }
    

提交回复
热议问题