需求如下:
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 }
原文地址:https://www.cnblogs.com/evilr/p/12024081.html
时间: 2024-11-09 05:27:12