简体   繁体   中英

Javascript - push into JSON array

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 ?

You actually have an object inside your array.

updatedData.updatedValues[0].c = 0; 

will result in your desired outcome.

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});

您正在将某些内容推送到更新的值数组,而不是在数组的第0个元素上设置属性。

updatedData.updatedValues[0].c = 0;

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

updatedData.updatedValues[0]['c']=0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM