树转二维数组的方法

需求如下:

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 }
    ]
]

 

方法:

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
}
上一篇:python 图像处理(7):对比度与亮度调整


下一篇:递归列出目录文件