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?

1

4 Answers 4

5

You actually have an object inside your array.

updatedData.updatedValues[0].c = 0; 

will result in your desired outcome.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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;

Comments

1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.