所以我正在尝试编写一个递归函数,该函数采用平面对象数组及其值、id 和它们的父节点的 id,并将其转换为树结构,其中结构的子节点是一个数组的节点。 children 需要按 id 排序,如果它的 null
它可以是根节点。
我试图将函数写入到 Tree(data) 中的函数,只应接收数据数组。没有 parent ,我无法做到这一点。到目前为止,我所拥有的是一个函数(如下),它需要数据和父项才能开始。
输入:
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;
}
我真的很想了解有关如何执行此操作的正确逻辑,并考虑此操作以及如何在不明确提供父级的情况下执行此操作。
最佳答案
我在面试的时候也遇到了同样的问题,一直没能解决。我也很困惑,该函数应该只将数组作为第一个也是唯一的参数。
但是在稍后重新设计之后(并且有一个聪明人的一些非常好的建议),我意识到你可以第一次使用数组作为第一个也是唯一的参数来调用函数,然后在传递父级的递归调用中作为第二个论点。
在函数内部,您只需要检查第二个参数是否未定义,如果是,则在数组中搜索您的根对象并将其分配给您的第二个参数。
所以这是我的解决方案,我希望它会更清楚:
function toTree(arr, item) {
if (!item) {
item = arr.find(item => item.parent === null)
}
let parent = {...item}
parent.children =
arr.filter(x => x.parent === item.id)
.sort((a, b) => a.id - b.id)
.map(y => toTree(arr, y))
return parent
}
toTree(tasks)
关于javascript - 创建一个采用平面数组并转换为树数据结构的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54566964/