面试了十几个高级前端,居然连(扁平数据结构转 Tree)都写不进去
具体题目详情点击下面查看,树转扁平做得多,扁平转树还真没写过。有意思。上午看到做个笔迹记录下。
扁平数据如下:
let arr = [{id: 1, name: '部门 1', pid: 0},
{id: 2, name: '部门 2', pid: 1},
{id: 3, name: '部门 3', pid: 1},
{id: 4, name: '部门 4', pid: 3},
{id: 5, name: '部门 5', pid: 4},
]
输入后果如下,有限层级的树:
[
{
"id": 1,
"name": "部门 1",
"pid": 0,
"children": [
{
"id": 2,
"name": "部门 2",
"pid": 1,
"children": []},
{
"id": 3,
"name": "部门 3",
"pid": 1,
"children": [// 后果 ,,,]
}
]
}
]
本人写的解答办法
const flap2Tree = (flapArr)=>{
// 递归依据 pid 找父
const findByPid = (pid, data)=> {for(let i=0; i<data.length; i++){if( data[i].id === pid ) {return data[i];
}else if(data[i].children && data[i].children.length){return pidFindParent(pid, data[i].children);
}
}
}
let resTree = [];
flapArr.forEach( t => {let myParent = findByPid(t.pid, afterArr);
if(myParent){myParent.children || (myParent.children = []); // 初始化
myParent.children.push(t);
}else{resTree.push(t);
}
})
return resTree;
}
flap2Tree(arr);
学习博主最优性能办法
function arrayToTree(items) {const result = []; // 寄存后果集
const itemMap = {}; //
for (const item of items) {
const id = item.id;
const pid = item.pid;
if (!itemMap[id]) {itemMap[id] = {children: [],
}
}
itemMap[id] = {
...item,
children: itemMap[id]['children']
}
const treeItem = itemMap[id];
if (pid === 0) {result.push(treeItem);
} else {if (!itemMap[pid]) {itemMap[pid] = {children: [],
}
}
itemMap[pid].children.push(treeItem)
}
}
return result;
}