我正在尝试编写一个递归函数,将具有值、id和其父节点id的对象的平面数组转换为树形结构,其中结构的子节点是节点数组。子节点需要按id排序,如果是
输入:
null
,则可以是根节点。我尝试编写的函数toTree(data)只应接受数据数组。但我无法在没有父级的情况下完成它。到目前为止,我拥有一个函数(如下),它需要使用数据和父级来开始。输入:
const tasks = [
{ id: 1, parent: null, value: 'Make breakfast' },
{ id: 2, parent: 1, value: 'Brew coffee' },
{ id: 3, parent: 2, value: 'Boil water' },
{ id: 4, parent: 2, value: 'Grind coffee beans' },
{ id: 5, parent: 2, value: 'Pour water over coffee grounds' }
];
输出:
{
id: 1,
parent: null,
value: 'Make Breakfast',
children: [
{
id: 2,
parent: 1,
value: 'Brew coffee',
children: [
{ id: 3, parent: 2, value: 'Boil water' },
{ id: 4, parent: 2, value: 'Grind coffee beans' },
{ id: 5, parent: 2, value: 'Pour water over coffee grounds' }
]
}
]
}
funciton toTree(data) {
customtoTree (data, null);
}
function customToTree (data, parent) {
const out = [];
data.forEach((obj) => {
if (obj.parent === parent) {
const children = customToTree(data,obj.parent);
if (children.length) {
obj[children[0]] = children;
}
const {id,parent, ...content} = obj;
out.push(content);
}
});
return out;
}
我非常希望能够理解如何正确地进行这项操作,思考如何在不显式指定父元素的情况下实现。