将键值对添加到Javascript对象中

时间:2015-11-10 07:45:29

标签: javascript node.js sails.js

我将获得以下对象作为查询结果。我想在每个Resourse.getPage(1,2,3) //what ever you want to pass its not necessory to pass the same as above .done(function(response){ //do what ever you want to do with response from your factory.. PHEW... }); 之后附加key3 : value3。我循环结果对象并尝试添加 一个类似于key2 : value2的状态,但它对我没用,任何人都可以帮助我。

loopedItem.status = "1"

2 个答案:

答案 0 :(得分:1)

    var x = [
      { 
       key1 : [
                {
                 "key1.1" : "value1.1" 
                },
                {
                 "key1.2" : "value1.2"
                }
               ],
       key2 : "value2"
      },
      { 
       key1 : [
                {
                 "key1.1" : "value1.1" 
                },
                {
                 "key1.2" : "value1.2"
                }
               ],
       key2 : "value2"
      }
    ]

for(var i=0;i<x.length;i++){
 var eachItem = x[i];
 eachItem['key3'] = 'value3';  // adds a key with value value3
}
console.log(x);

答案 1 :(得分:1)

试试这个:

objs = [
    {
        "key1" : [
            {
                "key1.1" : "value1.1"
            },
            {
                "key1.2" : "value1.2"
            }
        ],
        "key2" : "value2"
    },
    {
        "key1" : [
            {
                "key1.1" : "value1.1"
            },
            {
                "key1.2" : "value1.2"
            }
        ],
        "key2" : "value2"
    }
]


for (ele in objs) {
    objs[ele]["status"] = "1"
}
for (ele in objs) {
    console.log(objs[ele])
    console.log("\n" + "--------------------")


}