用JavaScript递归构建树

llo*_*ola 6 javascript algorithm recursion

我试图从一系列对象中递归构建一棵树。我目前正在使用该reduce()方法遍历数组中的项目,找出哪些孩子属于特定项目并填充它,然后递归地填充这些孩子的孩子,依此类推。但是,我一直无法取最后一个节点(例如,在这种情况下为波斯和暹罗)并将它们放在数组中(请参见下面的预期和当前输出)

    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));
Run Code Online (Sandbox Code Playgroud)

预期输出:

{
    "animals": {
        "mammals": {
            "cats": [     // <-- an array of cat strings
                "persian",
                "siamese"
            ],
            "dogs": [     // <-- an array of dog strings
                "chihuahua",
                "labrador"
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当前输出:

{
    "animals": {
        "mammals": {
            "cats": {       // <-- an object with cat keys
                "persian": {},
                "siamese": {}
            },
            "dogs": {       // <-- an object with dog keys
                "chihuahua": {},
                "labrador": {}
            }
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

我应该如何解决问题?

Vik*_*ngi 2

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

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));
Run Code Online (Sandbox Code Playgroud)
注意:如果您的数据结构再次更改,则此解析器可能会在其他情况下失败。