2012-04-07 59 views
1
storeChildren : function(coreid, data) { 
    $.each(data, function(id, type) { 
    $.core.children[coreid] = {}; 
    $.core.children[coreid]['id'] = id; 
    $.core.children[coreid]['type'] = type; 
    }); 
} 

($ .core.children是一個對象)的JavaScript多維數組/哈希表

我想要的結果數組/對象(我喜歡的對象),看起來像這樣(原諒我的PHP僞代碼):

array(coreid => array(id=>type, id=>type, id=>type)); 

我知道我每次運行循環時都覆蓋$ .core.children [coreid]我只是不知道如何修復它。

+0

我會使用一個對象,而不是'var obj = {key:value,key:value,...}' – elclanrs 2012-04-07 04:40:38

回答

2

如果你所有的id都是唯一的,那麼下面的內容應該可以工作;這是你在追求什麼?

storeChildren : function(coreid, data) { 
    $.core.children[coreid] = {}; 
    $.each(data, function(id, type) { 
    $.core.children[coreid][id] = type; 
    }); 
} 
+0

我所有的ID都是唯一的。非常明顯!謝謝。 – 2012-04-07 04:46:51

0
init: function() { 
    $.core.children = []; // instantiate array 
}, 

storeChildren : function(coreid, data) { 

    $.each(data, function(id, type) { 
     $.core.children[coreid] = {id : type}; 
    }); 
} 

實例化代碼別處對象,那麼你不會殺關聯數組/每次對象。上面的例子中也使用您的數組代替數組,結果,在JSON符號內的對象,如下所示:

[ {key,value} , {key,value} , {key,value} , ...] 

的COREID是數組的索引。