Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

javascript - 向对象添加元素(Adding elements to object)

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

(我需要填充一个json文件,现在我有了类似的东西:)

{"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.

(我的第一步是使用cart = JSON.parse将json放入Object类型,现在我需要添加新元素。)

I supposed I must use cart.push to add another element, I tried this:

(我以为我必须使用cart.push来添加另一个元素,我尝试了这个:)

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.

(但是,当我尝试执行element.push ,出现了“对象没有方法推送”错误,并且我认为我做错了很多,因为我没有在任何地方告诉“ element”。)

How can I do that?

(我怎样才能做到这一点?)

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

(编辑:对不起,我脑子里有些混乱。)

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.

(我以为从JSON.parse提取数据时只能得到对象类型,但是首先得到的是JSON中的内容。)

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

(用数组代替对象解决了我的问题,我也使用了很多建议,谢谢大家!)

  ask by HypeZ translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

(如果您希望购物车是{ element: { id: 10, quantity: 1} }形式的对象数组,请执行以下操作:)

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()中提到了JSON.stringify()作为关注点:)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...