const arr = [
{ id: 2, pid: 1,name:'bb' },
{ id: 3, pid: 1,name:'cc' },
{ id: 4, pid: 2,name:'dd' },
{ id: 1, pid: 0,name:'aa' },
{ id: 5, pid: 2,name:'ee' },
{ id: 6, pid: 3,name:'ff' },
];
function arr2tree (arr) {
// parentHash用于确定rootId,childHash用于构建树形结构
//步骤一:转化数组数据称为hash结构数据
const parentHash = {}, childHash = {};
for (let item of arr) {
const { id, pid,name } = item;
parentHash[id] = {pid:pid,name:name};
if (!childHash[pid]) {
childHash[pid] = [];
}
childHash[pid].push({id:id,name:name});
}
console.log('p=',parentHash);
console.log('c=',childHash)
//步骤二:确定树形结构的根节点
let rootId = arr[0].id;
while (parentHash[rootId] !== undefined) {
rootId = parentHash[rootId];
}
console.log('root=',rootId)
//步骤三:将hash结构转化为树形结构
return hash2Tree(childHash, rootId);
}
//函数作用:将hash结构转化为树形结构
function hash2Tree (childHash, rootId) {
let res = { id: rootId };
if (childHash[rootId] && childHash[rootId].length > 0) {
res.children = childHash[rootId].map((cid) => hash2Tree(childHash, cid))
}
return res;
}
let a = arr2tree(arr);
console.log(a)
console