gpt4 book ai didi

javascript - 在 JavaScript 中递归构建树

转载 作者:数据小太阳 更新时间:2023-10-29 05:24:20 32 4
gpt4 key购买 nike

我正在尝试从一组对象递归地构建一棵树。我目前正在使用 reduce() 方法遍历数组中的项目并找出哪些 child 属于特定项目并填充它,然后递归地填充这些 child 的 child 等等。但是,我一直无法获取最后一个节点(例如本例中的波斯语和暹罗语)并将它们放入数组中(请参阅下面的预期和当前输出)

    let categories = [
{ id: 'animals', parent: null },
{ id: 'mammals', parent: 'animals' },
{ id: 'cats', parent: 'mammals' },
{ id: 'dogs', parent: 'mammals' },
{ id: 'chihuahua', parent: 'dogs' },
{ id: 'labrador', parent: 'dogs' },
{ id: 'persian', parent: 'cats' },
{ id: 'siamese', parent: 'cats' }
];

const reduceTree = (categories, parent = null) =>
categories.reduce(
(tree, currentItem) => {

if(currentItem.parent == parent){
tree[currentItem.id] = reduceTree(categories, currentItem.id);
}

return tree;
},
{}
)

console.log(JSON.stringify(reduceTree(categories), null, 1));

预期输出:

{
"animals": {
"mammals": {
"cats": [ // <-- an array of cat strings
"persian",
"siamese"
],
"dogs": [ // <-- an array of dog strings
"chihuahua",
"labrador"
]
}
}
}

当前输出:

{
"animals": {
"mammals": {
"cats": { // <-- an object with cat keys
"persian": {},
"siamese": {}
},
"dogs": { // <-- an object with dog keys
"chihuahua": {},
"labrador": {}
}
}
}
}

我应该如何解决这个问题?

最佳答案

如果节点没有子节点,我会设置一个条件将结果合并为一个数组。试试这个

let categories = [
{ id: 'animals', parent: null },
{ id: 'mammals', parent: 'animals' },
{ id: 'cats', parent: 'mammals' },
{ id: 'dogs', parent: 'mammals' },
{ id: 'chihuahua', parent: 'dogs' },
{ id: 'labrador', parent: 'dogs' },
{ id: 'persian', parent: 'cats' },
{ id: 'siamese', parent: 'cats' }
];

const reduceTree = (categories, parent = null) =>
categories.reduce(
(tree, currentItem) => {

if(currentItem.parent == parent){
let val = reduceTree(categories, currentItem.id);
if( Object.keys(val).length == 0){
Object.keys(tree).length == 0 ? tree = [currentItem.id] : tree.push(currentItem.id);
}
else{
tree[currentItem.id] = val;
}
}
return tree;
},
{}
)

console.log(JSON.stringify(reduceTree(categories), null, 1));
注意:如果您的数据结构再次更改,此解析器可能会在某些其他情况下失败。

关于javascript - 在 JavaScript 中递归构建树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56389058/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com