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

如何将无限嵌套对象的children键递归替换为数字键?

解决方案

可以通过递归函数实现这个转换逻辑,核心是跟踪当前的层级数字,每深入一层children就递增数字,直到遇到空children时终止递归并返回对应结构。

代码实现(单分支场景,匹配你的示例)

function convertToNumberKeys(obj, currentNum = 1) {
    // 终止条件:当前节点没有子节点时,返回当前数字键对应空字符串的对象
    if (!obj.children || obj.children.length === 0) {
        return { [currentNum]: '' };
    }
    
    // 取当前节点的第一个子节点(匹配示例中每个层级仅一个子节点的情况)
    const child = obj.children[0];
    // 递归处理子节点,层级数字+1
    const nextLevel = convertToNumberKeys(child, currentNum + 1);
    
    // 返回当前层级的结构
    return { [currentNum]: nextLevel };
}

// 测试示例输入
const input = {
  children: [
    {
      taskId: "e3f241f8-c879-4118-893d-a16715e45308",
      opts: {},
      children: [
        {
          taskId: "e3f241f8-c879-4118-893d-a248cae411208",
          opts: {},
          children: [
            {
              taskId: "e3f241f8-c879-4118-89112d-s248cae411208",
              opts: {},
              children: []
            }
          ]
        }
      ],
    }
  ],
};

console.log(convertToNumberKeys(input));

代码说明

  1. 递归终止条件:当当前对象的children数组为空时,返回一个以当前层级数字为键、空字符串为值的对象,对应你期望输出的最内层结构。
  2. 递归处理子节点:如果当前节点有子节点,取第一个子节点(示例中每个层级只有一个子节点),递归调用函数并将层级数字加1,得到子节点转换后的结构。
  3. 构建当前层级结构:将递归得到的子层级结构作为当前数字键的值,返回给上一层。

多分支场景扩展(可选)

如果你的实际数据中存在一个节点有多个子节点的情况,可以修改函数来处理多分支:

function convertToNumberKeys(obj, baseNum = 1) {
    if (!obj.children || obj.children.length === 0) {
        return { [baseNum]: '' };
    }
    
    const result = {};
    obj.children.forEach((child, index) => {
        // 每个子分支从baseNum+1开始计数,分支间数字连续递增
        const currentKey = baseNum + index + 1;
        result[currentKey] = convertToNumberKeys(child, currentKey);
    });
    
    return result;
}

比如输入一个有两个子节点的结构,会生成类似{1: {2: '', 3: {4: ''}}}的输出。

内容的提问来源于stack exchange,提问作者DIOP 34K

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:07:41