树转为二维数组的问题

Tenadolanter
  • 98
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 }
    ]
]

没思路了,有好办法吗

评论
阅读 478
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"
        }
    ]
]
撰写回答

登录后参与交流、获取后续更新提醒

宣传栏