构建目录树结构

// 示例节点结构  
        const nodes = [  
            { id: 1, parentId: null, name: 'Root' },  
            
            { id: 4, parentId: 2, name: 'Grandchild 1' },  
            { id: 5, parentId: 2, name: 'Grandchild 2' },  
            { id: 3, parentId: 1, name: 'Child 2' },  
            { id: 2, parentId: 1, name: 'Child 1' },  
        ];  
        
        // 辅助函数:通过id查找节点  
        function findNodeById(tree, id) {  
            if (!tree || !tree.length) return null;  
        
            for (let node of tree) {  
                if (node.id === id) {  
                    return node;  
                } else if (node.children && node.children.length) {  
                    const found = findNodeById(node.children, id);  
                    if (found) {  
                        return found;  
                    }  
                }  
            }  
            return null;  
        }  
        
        // 主函数:构建树结构  
        function buildTree(nodes, parentId = null) {  
            console.log(nodes,11111)
            return nodes  
                .filter(node => node.parentId === parentId) // 筛选出当前层级的节点  
                .map(node => ({  
                    ...node,  
                    children: buildTree(nodes, node.id) // 递归构建子节点  
                }));  
        }  
        
        // 构建树  
        const tree = buildTree(nodes);  
        console.log(tree,1123)
        // 通过id查询节点  
        const nodeIdToFind = 1;  
        const foundNode = findNodeById(tree, nodeIdToFind);  
        
        console.log(foundNode); // 输出: { id: 4, parentId: 2, name: 'Grandchild 1', children: [] }

  

posted @ 2024-11-27 11:16  国服第一李师师  阅读(2)  评论(0编辑  收藏  举报