如何将元素插入json数组

时间:2013-10-29 06:21:54

标签: javascript json

我有这样的json:

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

我动态地获取这个json,我将这个json存储在adlist中。我想将元素插入到第三个位置的数组中。我试过这样:

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

但它没有正确添加字符串。

3 个答案:

答案 0 :(得分:2)

尝试

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

答案 1 :(得分:1)

您也可以尝试这样做以获得更好的性能,

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

答案 2 :(得分:0)

这对我有用:)

Javascript代码:

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