我有一个像下面的对象
var obj = [
{ name : ["a", "x", "1"] , d : [1,2,3] },
{ name : ["a", "x", "2"] , d : [1,2,3] },
{ name : ["a", "y", "3"] , d : [1,2,3] },
{ name : ["a", "y", "4"] , d : [1,2,3] },
{ name : ["a", "z", "5"] , d : [1,2,3] },
{ name : ["a", "z", "6"] , d : [1,2,3] },
{ name : ["b", "x", "7"] , d : [1,2,3] },
{ name : ["b", "x", "9"] , d : [1,2,3] }
];
以上name
数组长度可以是任何..我需要将数组分组如下
formatted = {
a : {
x : {
1 : [1,2,3],
2 : [1,2,3]
},
y : {
3 : [1,2,3],
4 : [1,2,3]
},
z : {
5 : [1,2,3],
6 : [1,2,3]
}
},
b : {
x : {
7 : [1,2,3],
8 : [1,2,3]
}
}
}
有没有可用的算法。请帮我实现这个逻辑。
答案 0 :(得分:0)
尝试类似
的内容var formatted = {}, inner, i, j;
for(i = 0; i < obj.length; i++){
expand(formatted, obj[i].name, obj[i].d)
}
function expand(obj, array, value){
var key, temp;
if(array.length == 1){
obj[array.shift()] = value;
} else {
key = array.shift();
temp = obj[key] = obj[key] || {};
expand(temp, array, value)
}
}
演示:Fiddle
答案 1 :(得分:0)
此功能从解决了我的问题。感谢Feliz Kling的建议
function setToValue(obj, value, path) {
var parent = obj;
for (var i = 0; i < path.length - 1; i += 1) {
parent[path[i]] = parent[path[i]] || {}
parent = parent[path[i]];
}
parent[path[path.length-1]] = value;
}