数组转树形
递归转换
function arrToTree(arr, pid = 0) {
let result = [];
arr.forEach((item) => {
if (item.pid == pid) {
item.children = arrToTree(arr, item.id);
result.push(item);
}
});
return result;
}
巧用map对象
function arrToTree(arr) {
let result = [],
map = new Map(),
sourceArr = JSON.parse(JSON.stringfy(arr));
sourceArr.forEach((item) => {
map.set(item.id, item);
if (item.pid == 0) {
result.push(item);
} else {
let mapVal = map.get(item.pid);
if (mapVal) {
if (!mapVal.children) {
mapVal.children = [];
}
mapVal.children.push(item);
}
}
});
return result;
}
树形转数组
递归转换
function treeToArr(tree, arr = []) {
tree.forEach((item) => {
let { children, ...others } = item;
arr.push(others);
if (children?.length) {
treeToArr(item.children, arr);
}
});
return arr;
}