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

JavaScript中将扁平数组转换为指定层级嵌套树数组的实现问题

实现思路
  • 用Map做临时索引分别存储已生成的Group、Act节点,避免重复创建同层级同名节点
  • 遍历扁平数组的每一项,按Group→Act→属性的顺序逐层检查/创建节点并挂载上下级关联
  • 最后提取所有Group节点转为数组,即为完整的嵌套树结构
实现代码
function flatToTree(aTree) {
  const groupMap = new Map()
  // act的key拼接Group前缀,避免不同Group下同名Act冲突
  const actMap = new Map()

  aTree.forEach(item => {
    const { Group, Act, Work, Pname, Pvalue, Pcount } = item

    // 处理Group层级
    if (!groupMap.has(Group)) {
      groupMap.set(Group, {
        label: Group,
        type: 'group',
        children: []
      })
    }
    const currentGroup = groupMap.get(Group)

    // 处理Act层级
    const actKey = `${Group}-${Act}`
    if (!actMap.has(actKey)) {
      const actNode = {
        label: Act,
        type: 'act',
        children: []
      }
      actMap.set(actKey, actNode)
      currentGroup.children.push(actNode)
    }
    const currentAct = actMap.get(actKey)

    // 处理属性层级,直接挂载到对应Act下
    currentAct.children.push({
      label: Pname,
      type: 'property',
      Work,
      Pvalue,
      Pcount
    })
  })

  return Array.from(groupMap.values())
}
调用示例

输入示例:

const demoData = [
  { Group: '运营组', Act: '用户拉新', Work: '线上投放', Pname: '曝光量', Pvalue: 15000, Pcount: 28 },
  { Group: '运营组', Act: '用户拉新', Work: '线下地推', Pname: '注册转化率', Pvalue: '32%', Pcount: 6 },
  { Group: '产品组', Act: '版本迭代', Work: '首页改版', Pname: '需求完成率', Pvalue: '95%', Pcount: 4 }
]

调用flatToTree(demoData)即可得到符合要求的三级嵌套树结构,节点字段可根据实际业务需求自行调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 18:36:07