构建目录树结构
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: [] } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?