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

如何为嵌套JavaScript对象的子元素添加父元素ID属性

给嵌套的JavaScript对象添加parentId属性

需求说明

处理一个支持无限嵌套的JavaScript对象结构,为每个有父元素的节点添加parentId属性,值对应其父节点的id。当节点没有children或children为空数组时,停止递归处理。

输入示例

{
  type: "ul",
  id: "1",
  children: [
    {
      type: "li",
      id: "2",
      children: [
        {
          type: "ul",
          id: "3",
          children: [...]
        }
      ]
    }
  ]
}

输出示例

{
  type: "ul",
  id: "1",
  children: [
    {
      type: "li",
      id: "2",
      parentId: "1",
      children: [
        {
          type: "ul",
          id: "3",
          parentId: "2",
          children: [...]
        }
      ]
    }
  ]
}

实现方案

用递归函数遍历嵌套结构,为每个子节点添加parentId:

function addParentIds(node, parentId) {
  // 无children或children为空时终止递归
  if (!node.children || node.children.length === 0) return;

  node.children.forEach(child => {
    // 为子节点添加parentId
    child.parentId = parentId;
    // 递归处理子节点的children
    addParentIds(child, child.id);
  });
}

// 使用示例
const originalData = {
  type: "ul",
  id: "1",
  children: [
    {
      type: "li",
      id: "2",
      children: [
        {
          type: "ul",
          id: "3",
          children: []
        }
      ]
    }
  ]
};

// 执行处理
addParentIds(originalData, originalData.id);
console.log(originalData);

补充说明

  • 上述代码会直接修改原对象,若需保留原数据,可先深拷贝一份再处理:
    const clonedData = structuredClone(originalData);
    addParentIds(clonedData, clonedData.id);
    
  • 递归逻辑自动适配无限嵌套的children结构,只要存在非空children数组就会继续遍历处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:15:44