let arr = [
{ id: 2, name: "部门B", parentId: 0 },
{ id: 3, name: "部门C", parentId: 1 },
{ id: 1, name: "部门A", parentId: 2 },
{ id: 4, name: "部门D", parentId: 1 },
{ id: 5, name: "部门E", parentId: 2 },
{ id: 6, name: "部门F", parentId: 3 },
{ id: 7, name: "部门G", parentId: 2 },
{ id: 8, name: "部门H", parentId: 4 },
];
/* function listToTree(oldArr) {
oldArr.forEach((element) => {
let parentId = element.parentId;
if (parentId !== 0) {
oldArr.forEach((ele) => {
if (ele.id == parentId) {
//当内层循环的ID== 外层循环的parendId时,(说明有children),需要往该内层id里建个children并push对应的数组;
if (!ele.children) {
ele.children = [];
}
ele.children.push(element);
}
});
}
});
// console.log(oldArr); //此时的数组是在原基础上补充了children;
oldArr = oldArr.filter((ele) => ele.parentId === 0); //这一步是过滤,按树展开,将多余的数组剔除;
// console.log(oldArr);
return oldArr;
}
*/
function transTree(data) {
let result = [];
let map = {};
if (!Array.isArray(data)) {
//验证data是不是数组类型
return [];
}
data.forEach((item) => {
//建立每个数组元素id和该对象的关系
map[item.id] = item; //这里可以理解为浅拷贝,共享引用
});
data.forEach((item) => {
let parent = map[item.parentId]; //找到data中每一项item的爸爸
if (parent) {
//说明元素有爸爸,把元素放在爸爸的children下面
(parent.children || (parent.children = [])).push(item);
} else {
//说明元素没有爸爸,是根节点,把节点push到最终结果中
result.push(item); //item是对象的引用
}
});
return result; //数组里的对象和data是共享的
}
console.log(transTree(arr));
参考:https://www.jianshu.com/p/bbdc8178a2dc
https://www.jb51.net/article/167897.htm