最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - push into JSON array - Stack Overflow

programmeradmin1浏览0评论

Just trying to update a JSON array and hoping for some guidance.

var updatedData = { updatedValues: [{a:0,b:0}]};    
updatedData.updatedValues.push({c:0}); 

That will give me:

{updatedValues: [{a: 0, b: 0}, {c: 0}]}

How can I make it so that "c" is part of that original array? So I end up with {a: 0, b: 0, c: 0} in updatedValues?

Just trying to update a JSON array and hoping for some guidance.

var updatedData = { updatedValues: [{a:0,b:0}]};    
updatedData.updatedValues.push({c:0}); 

That will give me:

{updatedValues: [{a: 0, b: 0}, {c: 0}]}

How can I make it so that "c" is part of that original array? So I end up with {a: 0, b: 0, c: 0} in updatedValues?

Share Improve this question asked May 18, 2015 at 4:52 b85411b85411 10.1k15 gold badges71 silver badges126 bronze badges 1
  • possible duplicate of Adding/removing items from JSON data with JQuery – Abhishek Commented May 18, 2015 at 4:55
Add a ment  | 

4 Answers 4

Reset to default 5

You actually have an object inside your array.

updatedData.updatedValues[0].c = 0; 

will result in your desired oute.

The updatedValues is a plain object and you have to add c as property.

var updatedData = { updatedValues: [{a:0,b:0}]};    
updatedData.updatedValues[0]["c"] = 0;

If you are using jquery then do as follows.

var updatedData = { updatedValues: [{a:0,b:0}]};    
$.extend(updatedData.updatedValues[0],{c:0});

You're pushing something to the updated values array, rather than setting an attribute on the 0th element of the array.

updatedData.updatedValues[0].c = 0;

You can add an item in the object. This should work.

updatedData.updatedValues[0]['c']=0;
发布评论

评论列表(0)

  1. 暂无评论