扁平数据结构转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',p
·
直接上代码
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
},
]
//只需要一次循环就可以解决
function arrayToTree(items){
const resule = []; //放结果集
const itemMap = {}; //Map结构
for(const item of items){
const id = item.id;
const pid = item.pid;
//创建Map,里面存放以id为键,空对象{children: [],}为值的键值对
if(!itemMap[id]){
item[id] = {
children:[],
}
// 然后我们在复制item里面已经有的属性作为对象的属性
itemMap[id] = {
...item,
children:[],
}
// 使得treeItem树里面的节点是map数据结构的键取出的值
const treeItem = itemMap[id];
//然后开始构造树
if(pid == 0){
result.push(treeItem);
}else{
if(!itemMap[pid]){
//如果itemMap[pid]不存在,说明他现在不在这棵树上
itemMap = {
children:[],
}
}
itemMap[pid].children.push(treeItem);
}
}
return result;
}

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)