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

如何编写JS可复用递归函数将对象数组转换为指定树形结构?

原有代码问题分析

  • 数组类型判断错误:typeof v === Array 写法无效,typeof 检测数组返回值为object,正确判断数组需使用Array.isArray()
  • 未构造新对象:代码中声明的data数组未实际使用,最后直接返回原对象,未完成修改
  • 缺失nodes到children的转换逻辑,递归调用未承接返回值

实现方案

基础版(匹配你的需求)

// 递归转换单个节点
function transformNode(rawNode) {
  // 仅保留重命名后的名称字段
  const newNode = {
    name: rawNode.nodeName
  }
  // 存在子节点时递归处理所有子节点,重命名为children
  if (Array.isArray(rawNode.nodes)) {
    newNode.children = rawNode.nodes.map(child => transformNode(child))
  }
  return newNode
}

// 调用示例
// input为你给出的输入对象
const output = {
  name: input.node.map(item => transformNode(item))
}

通用可复用版(支持自定义键名映射)

/**
 * 嵌套节点转换工具
 * @param {Array} rawNodes 原始节点数组
 * @param {Object} keyMap 键名映射规则,默认 {nodeName: 'name', nodes: 'children'}
 * @returns {Array} 转换后的节点数组
 */
function transformNestedNodes(rawNodes, keyMap = {nodeName: 'name', nodes: 'children'}) {
  const [originNameKey, targetNameKey] = Object.entries(keyMap)[0]
  const [originChildrenKey, targetChildrenKey] = Object.entries(keyMap)[1]
  
  return rawNodes.map(rawNode => {
    const processedNode = {
      [targetNameKey]: rawNode[originNameKey]
    }
    if (Array.isArray(rawNode[originChildrenKey])) {
      processedNode[targetChildrenKey] = transformNestedNodes(rawNode[originChildrenKey], keyMap)
    }
    return processedNode
  })
}

// 调用示例
const output = {
  name: transformNestedNodes(input.node)
}

以上实现会自动过滤所有非目标字段,递归处理所有层级的嵌套节点,输出结果和你给出的预期完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 06:57:03