2016-08-15 118 views
-4

我知道有push()將oject添加到數組中。但是如何將對象添加到對象中。如何在javascript中將對象添加到對象中

var osubcategories = {}; 

for (var i=0; i<data.length; ++i){ 
     var tempkey = data[i].scid; // here tempkey will be any number sat 15 20 30 etc 

     // how to add this tempkey along with true in osubcategories 
} 

我想這樣的輸出爲每個tempkey在循環:

osubcategories = {"15" : true, "23": true, "55" : true} 
+1

的可能的複製[我如何添加一個鍵/值對JavaScript對象?(http://stackoverflow.com/questions/1168807/how-can-i-add-a -key-value-pair-to-a-javascript-object) –

+0

'osubcategories [tempkey] = true;'在循環中 – coyer

回答

2

如何osubcategories[tempkey] = true;

編輯:忘記tempkey

+0

那'tempkey'在那裏有很多魔法...... –

+0

我不確定我是否收到您的評論。 –

+0

tempkey應該是一個臨時密鑰。在某些情況下,您希望在函數/代碼中保持密鑰的唯一性。雖然體面的回答。 :) –

1
var osubcategories = {}; 
for (var i=0; i<data.length; ++i){ 
    var tempkey = data[i].scid; // here tempkey will be any number sat 15 20 30 etc 
    // the following line will add the properties to the "osubcategories" object 
    osubcategories[tempKey] = true; 
} 
0

這個怎麼樣..

var osubcategories = {}; 
 
var data = [15,20,30]; 
 
var tempkey = {}; 
 
for (var i=0; i<data.length; ++i){ 
 
     osubcategories[data[i]] = true; 
 
} 
 
console.log(osubcategories);

相關問題