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

JavaScript递归返回undefined 如何将MongoDB嵌套子ID转为对应对象

你的代码存在以下几处核心问题,直接导致递归返回undefined:
  • 两个函数均缺少顶层返回值:get_documents和child_recursion都没有在函数最外层返回计算好的结果,函数执行完自然返回undefined。
  • 递归函数的返回位置完全错误:你把child_recursion的return语句写在了map方法的回调函数内部,且判断条件newChild === []永远不成立(引用类型的数组比较的是内存地址而非内容),就算条件成立,return也只会跳出当前map的回调,不会返回整个formattedData数组。
  • 递归触发条件错误:你写的是if (child.children.length > 1)才触发递归,那如果children长度为1就会跳过处理,不符合你要遍历所有层级的需求,应该改为只要child.children.length > 0就递归。
  • 变量作用域问题:child_recursion内部直接使用documents变量,但你没有把它作为参数传入递归函数,一旦child_recursion不在get_documents的作用域内,就会直接报错找不到documents。
  • map方法使用不当:map本身会返回处理后的新数组,你不需要额外声明空数组再push,要么直接用forEach做遍历,要么直接接收map的返回值,冗余写法也提高了出错概率。
修正后的参考代码:
const get_documents = (documents) => {
  // 先找根节点(parent为null的节点,这里假设根节点唯一)
  const root = documents.find(doc => doc.parent === null);
  if (!root) return [];

  // 递归处理子节点的内部函数,直接共享documents变量,避免作用域问题
  const formatChildren = (childIds) => {
    return childIds.map(id => {
      const child = documents.find(x => x._id === id);
      if (!child) return null;
      return {
        id: child._id,
        name: child.name,
        depth: 0,
        parent: child.parent,
        closed: true,
        // 只要有子节点就递归处理
        children: child.children.length > 0 ? formatChildren(child.children) : []
      }
    }).filter(Boolean);
  };

  // 返回格式化后的根节点,包含所有嵌套子节点
  return {
    id: root._id,
    name: root.name,
    depth: 0,
    parent: root.parent,
    closed: true,
    children: formatChildren(root.children)
  }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 16:45:03