数组转tree
let arr = [
{id: 2, name: "部门2", pid: 1},
{id: 1, name: "部门1", pid: 0},
{id: 3, name: "部门3", pid: 1},
{id: 4, name: "部门4", pid: 3},
{id: 5, name: "部门5", pid: 4},
];
console.log(arrtoTree(arr));
function arrtoTree() {
let map = new Map();
let res = arr.map((item) => {
return getChild(item, arr, map);
});
return res;
}
function getChild(params, arr, map) {
//判断是否寻找过
if (map.has(params.id)) {
return map.get(params.id);
}
//寻找符合项
let res = arr.filter((item) => item.pid === params.id);
if (res.length > 0) {
res = res.map((item) => {
return getChild(item, arr, map);
});
}
params.children = res;
//缓存数据
map.set(params.id, params);
return params;
}