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

如何通过递归函数与传引用构建未知深度的嵌套多维数组

我明白你卡在递归构建嵌套数组这事儿上了——明明子类信息是对的,但就是没法生成多层嵌套结构,反而只得到一维数组对吧?别慌,咱们来一步步解决这个问题。

问题根源分析

你当前的递归实现大概率犯了一个常见错误:没有把递归生成的子数组挂载到父元素的对应属性上,而是把所有元素直接平推到了同一个顶层数组里,自然就只能得到一维结果。

正确的递归实现示例

假设你的原始数据是类似这样的结构(通过parentId关联父子节点):

const rawData = [
  { id: 1, name: '父节点1', parentId: null },
  { id: 2, name: '子节点1-1', parentId: 1 },
  { id: 3, name: '子节点1-2', parentId: 1 },
  { id: 4, name: '孙节点1-2-1', parentId: 3 },
  { id: 5, name: '父节点2', parentId: null }
];

下面是能生成嵌套数组的递归函数:

function buildNestedArray(items, parentId = null) {
  // 筛选当前父节点下的所有子元素
  const children = items.filter(item => item.parentId === parentId);

  // 终止条件:没有子元素时返回空数组
  if (children.length === 0) {
    return [];
  }

  // 对每个子元素递归生成它的嵌套子数组,并挂载到children属性上
  return children.map(child => ({
    ...child,
    children: buildNestedArray(items, child.id)
  }));
}

核心逻辑说明

  1. 递归的本质是嵌套关联:每个节点都要把自己的子节点数组作为自身的一个属性(比如这里的children),而不是把所有节点都塞进同一个顶层数组。
  2. 用map替代push:map会返回新数组,每个元素都带上自己的嵌套子结构,完美契合嵌套数组的生成需求。
  3. 明确终止条件:当某个节点没有子元素时返回空数组,避免无限递归,同时保证结构的完整性。

调用示例与结果

执行const nestedResult = buildNestedArray(rawData);后,你会得到如下嵌套结构:

[
  {
    "id": 1,
    "name": "父节点1",
    "parentId": null,
    "children": [
      { "id": 2, "name": "子节点1-1", "parentId": 1, "children": [] },
      {
        "id": 3,
        "name": "子节点1-2",
        "parentId": 1,
        "children": [
          { "id": 4, "name": "孙节点1-2-1", "parentId": 3, "children": [] }
        ]
      }
    ]
  },
  { "id": 5, "name": "父节点2", "parentId": null, "children": [] }
]

灵活调整适配你的数据

如果你的数据不是用parentId关联父子,而是其他字段(比如parent、categoryId),只需要修改filter里的匹配条件即可。要是不需要保留原始的父关联字段(比如parentId),可以在map时剔除:

return children.map(({ parentId, ...rest }) => ({
  ...rest,
  children: buildNestedArray(items, rest.id)
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:23:11