码迷,mamicode.com
首页 > 编程语言 > 详细

树转二维数组的方法

时间:2019-12-11 18:56:11      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:bsp   isl   需求   res   二维数组   pat   color   ons   push   

需求如下:

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
}

树转二维数组的方法

标签:bsp   isl   需求   res   二维数组   pat   color   ons   push   

原文地址:https://www.cnblogs.com/evilr/p/12024081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!