2012-04-07 58 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是数组的索引。