Sunny
Sunny

Reputation: 1215

how to insert the element into the json array

I am having the json like this:

{
    json{
        "81":[
            {
            "name":"",
            "id":""
            },
            {
            "name":"",
            "id":""
            }
        ]
    }
}

I am getting this json dynamically and i am storing this json in adlist. I want to insert the element into the array in the third position. i tried like this:

 var temp={"name":"","id":""};
 adlist.json[81].splice(2,0,temp);

But it is not adding the string correctly.

Upvotes: 1

Views: 1057

Answers (3)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You can also try this too for better performance,

adlist.json["81"][adlist.json["81"].length]  ={name: "Douglas Adams", id: "comedy"};

Upvotes: 1

Nono
Nono

Reputation: 7302

It's working for me :)

Java Script Code:

//your json data
var adlist = {json:{"81":[{"name":"first","id":"1"},{"name":"second","id":"2"}]}};

// your new json data
var temp={"name":"Third","id":"3"};

// insert your new json data in 3rd position
adlist.json["81"].push(temp);

// check with console
console.log(adlist);

Upvotes: 0

amosmos
amosmos

Reputation: 1049

Try

adlist.81.push({name: "Douglas Adams", id: "comedy"});

Upvotes: 2

Related Questions