我有一个平面列表,如下所示。
flatList = [
{
id: "39000000",
parent: null,
description: "Electric Systems",
name: "39000000"
},
{
id: "39120000",
parent: "39000000",
description: "Electrical Equipment",
name: "39120000"
},
{
id: "39121000",
parent: "39120000",
description: "Power Conditioning",
name: "39121000"
},
{
id: "39121011",
parent: "39121000",
description: "Uninterruptible Power Supply",
name: "39121011"
}
];
从平面列表构造树并将树存储在nestedList中的方法
nestedList = [];
getTree(flatList) {
flatList.forEach(element => {
if (!element.parent) {
this.nestedList.push({ id: element.id, name: element.name, description: element.description, children: [] });
} else {
if (this.nestedList.findIndex(item => item.id === element.parent) === -1) {
this.nestedList.push({
id: element.id, name: element.name, description: element.description, children: [{ id: element.id, name: element.name, description: element.description, children: [] }]
});
} else {
this.nestedList.find(item => item.id === element.parent).children.push(
{ id: element.id, name: element.name, description: element.description, children: [] }
);
}
}
});
}
我得到的输出看起来像这样。
nestedList = [
{
id: "39000000",
name: "39000000",
description: "Electric Systems",
children: [{
id: "39120000",
name: "39120000",
description: "Electrical Equipment",
children: []}
]
},
{
id: "39121000",
name: "39121000",
description: "Power Conditioning",
children: [{
id: "39121000",
name: "39121000",
description: "Power Conditioning",
children: []
},
{
id: "39121011",
name: "39121011",
description: "Uninterruptible Power Supply",
children: []
}
]
}
]
期望的输出应该是:
nestedList = [
{
id: "39000000",
name: "39000000",
description: "Electric Systems",
children: [{
id: "39120000",
name: "39120000",
description: "Electrical Equipment",
children: [{
id: "39121000",
name: "39121000",
description: "Power Conditioning",
children: [{
id: "39121011",
name: "39121011",
description: "Uninterruptible Power Supply",
}]
}]
}]
}
]
帮助将不胜感激。
最佳答案
这是更现代的代码(下面有解释):
const src = [
{
id: "39000000",
parent: null,
description: "Electric Systems",
name: "39000000"
},
{
id: "39120000",
parent: "39000000",
description: "Electrical Equipment",
name: "39120000"
},
{
id: "39121000",
parent: "39120000",
description: "Power Conditioning",
name: "39121000"
},
{
id: "39121011",
parent: "39121000",
description: "Uninterruptible Power Supply",
name: "39121011"
}
];
const findChildren =
(parents, referenceArray) =>
parents.map(({ id, parent, description, name }) =>
({ id, description, name, children: findChildren(referenceArray.filter(i =>
i.parent === id), src) }))
console.log(findChildren(src.filter(i => i.parent === null), src))
- 代码找到根项 (
src.filter(i => i.parent === null)
)。 - 这些项目与引用数组(源数组)一起传递给
findChildren
函数。 findChildren
函数将旧对象映射到新格式(删除parent
,添加children
属性)...- ... 其中
children
属性是另一个findChildren
函数调用的结果,但参数是下一个根,即当前id
的 child >.
附言这也是完全非变异的解决方案,即不改变初始数组。
关于javascript - 从javascript中的平面列表构造一棵树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53993723/