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

如何用JavaScript高效实现对象数组按parent字段嵌套子对象

高效实现对象数组的父子嵌套转换

可以通过一次遍历+Map查找的方式实现O(n)时间复杂度的转换,这是效率最高的方案之一,具体实现如下:

实现代码

function nestChildren(data) {
  const map = new Map();
  const result = [];

  // 将所有对象存入Map,并初始化childs数组
  data.forEach(item => {
    map.set(item.id, { ...item, childs: [] });
  });

  // 遍历数据,将子元素挂载到对应父元素的childs中
  data.forEach(item => {
    if (item.parent) {
      const parent = map.get(item.parent);
      parent.childs.push(map.get(item.id));
    } else {
      // 无parent的元素是根节点,加入结果数组
      result.push(map.get(item.id));
    }
  });

  return result;
}

// 测试用例
const input = [
  { "id": 1, "animal": "cat", "age": 6, "name": "loky" },
  { "id": 2, "animal": "cat", "age": 3, "name": "michu", "parent": 1 },
  { "id": 3, "animal": "cat", "age": 2, "name": "boots", "parent": 1 },
  { "id": 4, "animal": "dog", "age": 9, "name": "bones" },
  { "id": 5, "animal": "dog", "age": 6, "name": "chok", "parent": 4 },
  { "id": 6, "animal": "dog", "age": 6, "name": "cofee","parent": 4 }
];

console.log(nestChildren(input));

代码说明

  1. Map存储引用:利用Map的O(1)查找特性,快速定位父对象,彻底避免嵌套循环带来的O(n²)复杂度
  2. 初始化childs数组:提前为每个对象创建childs数组,确保输出结构统一
  3. 一次遍历挂载子元素:第二次遍历仅负责子元素的挂载逻辑,简洁高效
  4. 收集根节点:没有parent属性的元素即为顶层节点,直接加入结果数组

输出结果

运行上述代码后,会得到你需要的嵌套结构:

[
  {
    "id": 1,
    "animal": "cat",
    "age": 6,
    "name": "loky",
    "childs": [
      { "id": 2, "animal": "cat", "age": 3, "name": "michu", "parent": 1 },
      { "id": 3, "animal": "cat", "age": 2, "name": "boots", "parent": 1 }
    ]
  },
  {
    "id": 4,
    "animal": "dog",
    "age": 9,
    "name": "bones",
    "childs": [
      { "id": 5, "animal": "dog", "age": 6, "name": "chok", "parent": 4 },
      { "id": 6, "animal": "dog", "age": 6, "name": "cofee", "parent": 4 }
    ]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 22:46:03