2015-11-10 84 views
-6

以下是我正在查詢的結果。我想在每個key2 : value2之後附加key3 : value3。我打結果對象,並嘗試添加 狀態類似於loopedItem.status = "1"類似的東西,但它不適用於我任何人都可以幫我。將一個鍵值對添加到Javascript對象中

[ 
    { 
    key1 : [ 
      { 
      key1.1 : value1.1 
      }, 
      { 
      key1.2 : value1.2 
      } 
      ], 
    key2 : value2 
    }, 
    { 
    key1 : [ 
      { 
      key1.1 : value1.1 
      }, 
      { 
      key1.2 : value1.2 
      } 
      ], 
    key2 : value2 
    } 
] 
+0

你能解釋更多! – elkebirmed

+0

將您嘗試的代碼添加到您的問題中。 – AntiHeadshot

回答

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); 
+0

對不起,它不能正常工作 –

+0

發佈錯誤。 – guptakvgaurav

2

試試這個:

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" + "--------------------") 


} 
相關問題