向对象添加元素 [英] Adding elements to object
问题描述
我需要填充一个json文件,现在我有这样的东西:
I need to populate a json file, now I have something like this:
{"element":{"id":10,"quantity":1}}
我需要添加另一个元素。我的第一步是使用 cart = JSON.parse
将json放入Object类型,现在我需要添加新元素。
我想我必须使用 cart.push
来添加另一个元素,我试过这个:
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 supposed I must use cart.push
to add another element, I tried this:
var element = {};
element.push({ id: id, quantity: quantity });
cart.push(element);
但是当我尝试 element.push
,我认为我做的事情非常错误,因为我没有在任何地方告诉元素。
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.
如何我能这样做吗?
编辑:对不起,我头脑中有很多困惑。
sorry to all I had a LOT of confusion in my head.
我认为从 JSON.parse
获取数据时我只能得到对象类型,但我得到了我在JSON中放置的内容。
I thought 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 lots of suggestions got here too, thank you all!
推荐答案
您的元素不是数组,但是您的购物车需要是一个数组才能支持许多元素对象。代码示例:
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);
如果您希望购物车成为形式的对象数组{element :{id:10,数量:1}}
然后执行:
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()
被提及为评论中的一个问题:
JSON.stringify()
was mentioned as a concern in the comment:
>> JSON.stringify([{a: 1}, {a: 2}])
"[{"a":1},{"a":2}]"
这篇关于向对象添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!