1

I want to insert one or more attributes into the existing JSON. Here's the basic format.

var resultData = {
        "result" : "OK",
        "data" : [
            {"name1" : "value1"},
            {"name2" : "value2"}
        ]
    };  

And I want to insert {"name3" : "value3"} into the end of the data field. The result should look like this.

var resultData = {
        "result" : "OK",
        "data" : [
            {"name1" : "value1"},
            {"name2" : "value2"},
            {"name3" : "value3"}
        ]
    };  

How do I do this? I know how to add an attribute to the resultData or resultData.result or resultData.data.name1 or etc. However, I couldn't find a way to add an attribute to the resultData.data.

2 Answers 2

1

You can do:

resultData.data[3] = {"name4" : "value4"}

That would add a new element on the 4th position. And like Sigorilla just answered before me, .push() will always add it one the end of your object.

You don't need to do resultData["data"].push() though, as you can just use resultData.data.push() I think.

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

Comments

1

You can use push(): resultData["data"].push({"name3": "value3"});

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.