如何从对象数组生成父子嵌套的层级树形结构?
数组转嵌套树形结构:问题分析与解决方案
你的代码错误
你当前的reduce逻辑是按type字段分组收集name值,完全没有利用parentId建立父子节点的关联关系,所以最终得到的是按类型分类的集合,而非预期的层级嵌套树形结构。
正确实现方式
我们可以通过构建节点映射+关联父子关系的方式实现树形结构:
- 先用
reduce创建一个以id为键、节点对象为值的映射表,方便快速查找父节点,同时给每个节点初始化children数组 - 遍历每个节点,将其添加到对应父节点的
children数组中 - 最后筛选出
parentId为"0"的根节点,作为树形结构的入口
完整代码
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"} ]; function buildTree(data) { // 构建id到节点的映射,同时初始化children数组 const nodeMap = data.reduce((map, node) => { map[node.id] = {...node, children: []}; return map; }, {}); const tree = []; // 遍历节点,关联父子关系 for (const node of Object.values(nodeMap)) { if (node.parentId === "0") { tree.push(node); } else { const parentNode = nodeMap[node.parentId]; parentNode?.children.push(node); } } return tree; } const result = buildTree(arrData); console.log(JSON.stringify(result, null, 2));
说明
- 代码统一使用
children(修正了你目标输出里的拼写错误childeren) - 映射表的构建让父节点查找的时间复杂度降到O(1),整体执行效率更高
- 逻辑清晰,先建立节点索引,再关联父子关系,最后提取根节点
内容的提问来源于stack exchange,提问作者Trupti
相关产品推荐
相关产品推荐

