如何将扁平数组转换为嵌套树形结构(JavaScript 实现)

本文详解如何基于 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助手,依托大模型,帮助用户记录、整理和分析音视频内容,体验用大模型做音视频笔记、整理会议记录。

相关推荐
夏至春来-美美1 天前
python 使用pytest的ini配置
开发语言·python·pytest
geovindu1 天前
python: Mutex Pattern
开发语言·python·设计模式·互斥锁模式
C137的本贾尼1 天前
告别硬编码:提示词模板入门
python·langchain
星纬智联技术1 天前
给 Amp 配置自定义 API:CLIProxyAPI 接入教程
运维·服务器·数据库
m0_372257021 天前
RRF和Cross-Encoder rerank怎么实现
开发语言·windows·python
浩~~1 天前
极客大挑战2019-LoveSQL
数据库
Cosolar1 天前
大模型应用开发面试 • 每日三题|Day 002|记忆(Memory)、工具使用(Tool Use)和微调(Fine-tuning)
后端·python·llm
码农阿豪1 天前
Go 语言操作金仓数据库(上篇):环境搭建与连接管理
开发语言·数据库·golang
Carl_奕然1 天前
【智能体】Agent的四种设计模式之:Plan-and-Execute
人工智能·python·设计模式
纤纡.1 天前
从课堂视频转写结构化数据:Python + 讯飞 + 通义千问全流程实战
python·阿里云·语言模型·讯飞