Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top