JavaScript:将含children的对象转换为步骤式数组
树形结构转逐步节点添加的步骤数组实现
要实现把嵌套树形结构转换成逐步添加节点的步骤数组,核心在于每次添加节点时都基于当前结构的深克隆来生成新步骤,避免对象引用导致的结构混乱。下面是具体实现方案:
实现步骤
- 深克隆工具函数:确保每个步骤的对象都是独立的,不会互相影响。
- 递归遍历生成步骤:从根节点开始,每添加一个节点就生成一个新的步骤,再递归处理子节点的添加过程。
完整代码
// 深克隆函数,处理对象和数组 function deepClone(obj) { if (obj === null || typeof obj !== 'object') return obj; if (obj instanceof Array) { return obj.map(item => deepClone(item)); } const cloned = {}; for (const key in obj) { if (obj.hasOwnProperty(key)) { cloned[key] = deepClone(obj[key]); } } return cloned; } // 生成步骤数组的递归函数 function generateSteps(tree) { const steps = []; // 第一步:仅根节点(不含children) const rootStep = { ...tree }; delete rootStep.children; steps.push(rootStep); // 递归处理子节点的添加过程 function traverse(parent, parentPath) { if (!parent.children || parent.children.length === 0) return; for (let i = 0; i < parent.children.length; i++) { const child = parent.children[i]; // 克隆当前最新的步骤结构 const currentStep = deepClone(steps[steps.length - 1]); // 根据父路径找到对应的父节点位置 let targetParent = currentStep; for (const path of parentPath) { targetParent = targetParent.children[path]; } // 初始化children(如果不存在) if (!targetParent.children) targetParent.children = []; // 添加当前子节点(先不含它的children) const childWithoutChildren = { ...child }; delete childWithoutChildren.children; targetParent.children.push(childWithoutChildren); // 加入步骤数组 steps.push(currentStep); // 递归处理当前子节点的子节点,更新父路径 traverse(child, [...parentPath, i]); } } // 从根节点开始遍历,父路径初始为空 traverse(tree, []); return steps; } // 测试示例 const data = { name: 'root', attributes: [{}], children: [ { name: 'child', attributes: [{}], children: [ { name: 'child', attributes: [{}], }, ], }, { name: 'child', attributes: [{}], }, ], }; const steps = generateSteps(data); console.log(steps);
代码说明
- 深克隆函数:处理对象和数组的递归克隆,保证每个步骤的结构都是独立的引用,不会出现修改后续步骤影响前面步骤的问题。
- 步骤生成逻辑:
- 第一步先添加不含子节点的根节点,作为初始步骤。
- 遍历每个子节点时,先克隆上一步的完整结构,通过父路径找到对应嵌套位置,添加当前子节点(先不含其子节点),生成新步骤。
- 递归处理当前子节点的子节点,父路径会记录当前节点在父节点
children中的索引,确保能精准定位嵌套层级。
- 最终生成的
steps数组完全符合你给出的示例结构,每个步骤都是在前一步基础上新增一个节点。
内容的提问来源于stack exchange,提问作者Wixome
相关产品推荐
相关产品推荐

