本文详解如何基于 parentid/id 关系,将一维对象数组高效构建为深度嵌套的树形结构,支持任意层级,并提供可直接运行的递归实现与关键注意事项。 本文详解如何基于 parentid/id 关系,将一维对象数组高效构建为深度嵌套的树形结构,支持任意层级,并提供可直接运行的递归实现与关键注意事项。在前端开发与数据可视化场景中,常需将后端返回的扁平化层级数据(如组织架构、设备拓扑、目录列表)转换为符合 DOM 渲染或组件库(如 Ant Design Tree、Element Plus ElTree)要求的嵌套树结构。核心挑战在于:正确识别父子关系、避免重复遍历、保证子节点按逻辑顺序挂载,且不破坏原始数据字段完整性。你当前使用的 reduce 按 type 分组的方式,本质上是横向分类(分组聚合),而非纵向层级构建------它丢失了 id 与 parentId 的引用链,自然无法生成嵌套的 children 数组。真正可行的方案是:以根节点为起点,递归查找所有 parentId 匹配当前节点 id 的子项,并为每个子项继续递归构造其子树。以下是一个简洁、健壮、无副作用的实现:function buildTree(data, rootId = '0') { // 使用 reduce 遍历全量数据,筛选出 parentId === 当前 rootId 的节点 return data.reduce((tree, node) => { if (node.parentId === rootId) { // 浅拷贝当前节点,避免污染原始数据 const newNode = { ...node }; // 递归构建其子树,并赋值给 children(注意:字段名统一为 children,非 childeren 拼写错误) newNode.children = buildTree(data, node.id); tree.push(newNode); } return tree; }, \[\]);}// 使用示例const arrData = { id: "3", name: "Ctech A", parentId: "0", type: "Building" }, { id: "4", name: "3rd floor", parentId: "3", type: "Floor" }, { id: "5", name: "room_01", parentId: "4", type: "Room" }, { id: "6", name: "room_video", parentId: "4", type: "Room" }, { id: "7", name: "room_Lab", parentId: "4", type: "Room" }, { id: "8", name: "room_engg", parentId: "4", type: "Room" }, { id: "9", name: "Rack_1", parentId: "5", type: "Rack" }, { id: "10", name: "Rack_2", parentId: "5", type: "Rack" }, { id: "11", name: "Rack_3", parentId: "5", type: "Rack" }, { id: "12", name: "Shelf_01", parentId: "9", type: "Shelf" }, { id: "13", name: "Slot_1", parentId: "12", type: "Slot" }, { id: "14", name: "Slot_2", parentId: "12", type: "Slot" }, { id: "15", name: "Shelf_02", parentId: "9", type: "Shelf" };const tree = buildTree(arrData);console.log(JSON.stringify(tree, null, 2));? 关键要点说明: 通义听悟 阿里云通义听悟是聚焦音视频内容的工作学习AI助手,依托大模型,帮助用户记录、整理和分析音视频内容,体验用大模型做音视频笔记、整理会议记录。
相关推荐
金銀銅鐵7 小时前
[Python] 基于欧几里得算法,实现分数约分计算器Lyn_Li9 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现小九九的爸爸13 小时前
前端想要入门Agent开发,要具备哪些Python基础?阿耶同学14 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构jiayou6415 小时前
KingbaseES 表级与列级加密完全指南花酒锄作田1 天前
Pydantic校验配置文件hboot1 天前
AI工程师第四课 - 深度学习入门GBASE1 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器