我有一个格式如下的数组
let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]},
{id:2, desc:'d2', children:[] },
{id:3, desc:'d3', children:[] }];
每个孩子与父元素同时出现的情况。我希望它将其转换为格式为{ [id]: {values} }
的对象:
{
1: { id: 1, desc: 'd1', children: {1.1: {id:1.1, desc:'d1.1'}},
2: { id:2, desc:'d2' },
3: { id:3, desc:'d3' }
}
我在很多方面都尝试过但没有成功。例如:
let obj = array.map(a => mapArrayToObj(a));
mapArrayToObj = (e) => {
let obj = {[e.id]: e };
if(e.children.lenght > 0){
e.children = e.children.map(c => mapArrayToObj(c));
}
else{
return {[e.id]: e };
}
}
在Javascript中是否可行?
答案 0 :(得分:3)
您可以使用递归函数,该函数从给定项目中生成对象而不会改变原始数据。
SELECT VALUE

function getObjects(array) {
var object = {};
array.forEach(function (item) {
object[item.id] = Object.assign({}, item, { children: getObjects(item.children) });
});
return object;
}
var array = [{ id: 1, desc: 'd1', children: [{ id: 1.1, desc: 'd1.1', children: [] }] }, { id: 2, desc: 'd2', children: [] }, { id: 3, desc: 'd3', children: [] }];
console.log(getObjects(array));

答案 1 :(得分:1)
让我们试试这段代码......
let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]},
{id:2, desc:'d2', children:[] },
{id:3, desc:'d3', children:[] }]
let object = {}
array.forEach(item => {
let children = item.children
object[item.id] = item
object[item.id].children = {}
children.forEach(child => {
object[item.id].children[child.id] = child
})
})
console.log(object)
结果:
{ '1': { id: 1, desc: 'd1', children: { '1.1': [Object] } },
'2': { id: 2, desc: 'd2', children: {} },
'3': { id: 3, desc: 'd3', children: {} } }
答案 2 :(得分:1)
您可以使用reduce()
方法创建递归函数并返回对象对象。
let array = [{id: 1, desc: 'd1', children:[{id:1.1, desc:'d1.1', children:[]}]}, {id:2, desc:'d2', children:[] }, {id:3, desc:'d3', children:[] }]
function build(data) {
return data.reduce(function(r, {id, desc, children}) {
const e = {id, desc}
if(children && children.length) e.children = build(children);
r[id] = e
return r;
}, {})
}
const result = build(array)
console.log(result)