You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript:将含children的对象转换为步骤式数组

树形结构转逐步节点添加的步骤数组实现

要实现把嵌套树形结构转换成逐步添加节点的步骤数组,核心在于每次添加节点时都基于当前结构的深克隆来生成新步骤,避免对象引用导致的结构混乱。下面是具体实现方案:

实现步骤

  1. 深克隆工具函数:确保每个步骤的对象都是独立的,不会互相影响。
  2. 递归遍历生成步骤:从根节点开始,每添加一个节点就生成一个新的步骤,再递归处理子节点的添加过程。

完整代码

// 深克隆函数,处理对象和数组
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);

代码说明

  • 深克隆函数:处理对象和数组的递归克隆,保证每个步骤的结构都是独立的引用,不会出现修改后续步骤影响前面步骤的问题。
  • 步骤生成逻辑:
    1. 第一步先添加不含子节点的根节点,作为初始步骤。
    2. 遍历每个子节点时,先克隆上一步的完整结构,通过父路径找到对应嵌套位置,添加当前子节点(先不含其子节点),生成新步骤。
    3. 递归处理当前子节点的子节点,父路径会记录当前节点在父节点children中的索引,确保能精准定位嵌套层级。
  • 最终生成的steps数组完全符合你给出的示例结构,每个步骤都是在前一步基础上新增一个节点。

内容的提问来源于stack exchange,提问作者Wixome

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:33:28