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

JavaScript递归构建JSON树形结构异常,如何修正嵌套数组问题?

递归生成层级JSON结构时的嵌套列表问题

我编写了一个递归函数用于生成层级JSON结构,但函数返回了非预期输出,尝试解决却毫无进展。输入格式为包含Name、Email、Reports to Id(父节点ID)和Id的对象列表,我已将该列表转换为以Reports to Id为键、直接汇报对象数组为值的Map(directReportee)。

错误的递归函数代码

function buildTree(mainRoot) {
  const items = [
    {
      label: mainRoot.Name,
      name: mainRoot.Name,
      expanded: true,
      items: [],
    },
  ];
  if (directReportee.has(mainRoot.Id)) {
    directReportee.get(mainRoot.Id).forEach((childNodes) => {
        items[0].items.push(buildTree(childNodes));
    });
  }
 
  return items;
}

当前错误输出

[
  {
    "label": "Lauren Boyle",
    "name": "Lauren Boyle",
    "expanded": true,
    "items": [
      [
        {
          "label": "Banoth Srikanth",
          "name": "Banoth Srikanth",
          "expanded": true,
          "items": [
            [
              {
                "label": "Stella Pavlova",
                "name": "Stella Pavlova",
                "expanded": true,
                "items": []
              }
            ]
          ]
        }
      ],
      [
        {
          "label": "Srikanth",
          "name": "Srikanth",
          "expanded": true,
          "items": []
        }
      ]
    ]
  }
]

期望的输出格式

items = [
        {
            label: 'Western Sales Director',
            name: '1',
            expanded: true,
            items: [
                {
                    label: 'Western Sales Manager',
                    name: '2',
                    expanded: true,
                    items: [
                        {
                            label: 'CA Sales Rep',
                            name: '3',
                            expanded: true,
                            items: [],
                        },
                        {
                            label: 'OR Sales Rep',
                            name: '4',
                            expanded: true,
                            items: [],
                        },
                    ],
                },
            ],
        }
    ]

问题原因与解决办法

问题核心是:你的buildTree函数返回的是包含单个节点的数组,但在递归调用时直接把这个数组push到items里,导致出现了数组嵌套数组的结构。

有两种修改方案:

方案1:让函数返回单个节点对象(推荐)

修改函数,直接返回单个节点对象而非数组,这样递归push的就是对象,不会产生嵌套:

function buildTree(mainRoot) {
  const node = {
    label: mainRoot.Name,
    name: mainRoot.Name,
    expanded: true,
    items: [],
  };
  if (directReportee.has(mainRoot.Id)) {
    directReportee.get(mainRoot.Id).forEach((childNode) => {
        node.items.push(buildTree(childNode));
    });
  }
 
  return node;
}

调用时如果需要根节点数组,再手动包裹:const tree = [buildTree(rootNode)];

方案2:保留函数返回数组,但push时取数组第一个元素

如果必须让函数返回数组,那在push递归结果时,取数组的第一个元素(也就是实际的节点对象):

function buildTree(mainRoot) {
  const items = [
    {
      label: mainRoot.Name,
      name: mainRoot.Name,
      expanded: true,
      items: [],
    },
  ];
  if (directReportee.has(mainRoot.Id)) {
    directReportee.get(mainRoot.Id).forEach((childNodes) => {
        // 取递归返回数组的第一个节点对象,避免嵌套
        items[0].items.push(buildTree(childNodes)[0]);
    });
  }
 
  return items;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:43:26