树转二维数组的方法

Posted evilr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了树转二维数组的方法相关的知识,希望对你有一定的参考价值。

需求如下:

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
}

以上是关于树转二维数组的方法的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段10—— 数组的响应式方法

树结构 无根树转有根树

c语言对二维数组的某一行赋值 如u8 a[20][20]; 仅对a[10]这一行赋值

C代码和python代码:用二维数组实现矩阵的转置

几个关于js数组方法reduce的经典片段

请问java中深度copy一个二维数组是啥意思?怎么用代码实现?