我正在尝试使用JavaScript从嵌套数组生成嵌套对象。但是到目前为止无法成功。
下面是数组示例。
let arr = [
'25',
'25_29',
'25_28',
'25_28_35',
'25_28_35_36',
'20',
'20_27',
'20_26',
'18',
'18_48',
'59',
'34'
];
下面是对象示例。
let Obj = {
25: {
key: 25,
child: {
29: {
key: 29, child: {}
},
28: {
key: 28,
child: {
key: 35,
child: {
key: 36,
child: {}
}
}
}
}
},
20: {
key: 20,
child: {
27: {
key: 27,
child: {}
},
26: {
key: 26,
child: {}
}
}
}
}
是否有可能这样做?
答案 0 :(得分:2)
let arr = ['25', '25_29', '25_28', '25_28_35', '25_28_35_36', '20', '20_27', '20_26', '18', '18_48', '59', '34'];
let obj = arr.reduce((obj, v) => {
let keys = v.split('_');
let o = obj;
keys.forEach(key => {
o[key] = o[key] || {key, child: {}};
o = o[key].child;
});
return obj;
}, {});
console.log(obj);
答案 1 :(得分:2)
您可以拆分路径并减少键。
var array = ['25', '25_29', '25_28', '25_28_35', '25_28_35_36', '20', '20_27', '20_26', '18', '18_48', '59', '34'],
result = array.reduce((r, s) => {
s.split('_').reduce((o, key) => (o[key] = o[key] || { key, child: {} }).child, r);
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }