构建目录树结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 示例节点结构 
        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 @   国服第一李师师  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
点击右上角即可分享
微信分享提示