树转二维数组的方法
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 }
以上是关于树转二维数组的方法的主要内容,如果未能解决你的问题,请参考以下文章