树转为二维数组的问题

let arr = [
  {
    code: "A001",
    level: 1,
    childs: [
      {
        code: "A002",
        level: 2,
        childs: [
          {
            code: "A005",
            level: 3,
            childs: []
          },
          {
            code: "A006",
            level: 3,
            childs: []
          }
        ]
      },
      {
        code: "A003",
        level: 2,
        childs: []
      },
      {
        code: "A004",
        level: 2,
        childs: []
      }
    ]
  }
];

转为二维数组:

[
    [
       { code: "A001", level: 1 },
       { code: "A002", level: 2 },
       { code: "A005", level: 3 },
    ],
    [
       { code: "A001", level: 1 },
       { code: "A002", level: 2 },
       { code: "A006", level: 3 },
    ],
    [
       { code: "A001", level: 1 },
       { code: "A003", level: 2 }
    ],
    [
       { code: "A001", level: 1 },
       { code: "A004", level: 2 }
    ]
]

没思路了,有好办法吗

阅读 2.5k
1 个回答

感谢邀请。


一次遍历完成,遍历过程中记录下路径,遍历到叶子节点则把路径加入到结果中。

有个问题是,child 的复数形式是children...不是childs,将错就错贴一个吧:

function traverse (tree, path = [], result = []) {
  if (!tree) return []
  for (const data of tree) {
    path.push({ level: data.level, code: data.code })
    let isLeaf = !data.childs || !data.childs.length
    isLeaf ? result.push([...path]) : traverse(data.childs, path, result)
    path.pop()
  }
  return result
}

测试:

let result = traverse(arr)
console.log(JSON.stringify(result))

输出:

[
    [
        {
            "level":1,
            "code":"A001"
        },
        {
            "level":2,
            "code":"A002"
        },
        {
            "level":3,
            "code":"A005"
        }
    ],
    [
        {
            "level":1,
            "code":"A001"
        },
        {
            "level":2,
            "code":"A002"
        },
        {
            "level":3,
            "code":"A006"
        }
    ],
    [
        {
            "level":1,
            "code":"A001"
        },
        {
            "level":2,
            "code":"A003"
        }
    ],
    [
        {
            "level":1,
            "code":"A001"
        },
        {
            "level":2,
            "code":"A004"
        }
    ]
]
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏