3

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?

b85411
  • 9,420
  • 15
  • 65
  • 119
  • possible duplicate of [Adding/removing items from JSON data with JQuery](http://stackoverflow.com/questions/4538269/adding-removing-items-from-json-data-with-jquery) – Abhishek May 18 '15 at 04:55

4 Answers4

5

You actually have an object inside your array.

updatedData.updatedValues[0].c = 0; 

will result in your desired outcome.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

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});
Madhu
  • 2,416
  • 3
  • 15
  • 33
1

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;

Luke
  • 1,724
  • 1
  • 12
  • 17
1

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

updatedData.updatedValues[0]['c']=0;
Anonymous Duck
  • 2,942
  • 1
  • 12
  • 35