递归展示菜单

const data = [
{ id: 1, name: "办公管理", pid: 0 },
{ id: 2, name: "请假申请", pid: 1 },
{ id: 3, name: "出差申请", pid: 1 },
{ id: 4, name: "请假记录", pid: 2 },
{ id: 5, name: "系统设置", pid: 0 },
{ id: 6, name: "权限管理", pid: 5 },
{ id: 7, name: "用户角色", pid: 6 },
{ id: 8, name: "菜单设置", pid: 6 },
];
function toTree(data) {
// 删除 所有 children,以防止多次调用
data.forEach(function (item) {
delete item.children;
});

// 将数据存储为 以 id 为 KEY 的 map 索引数据列
var map = {};
data.forEach(function (item) {
map[item.id] = item;
});
// console.log(map);
var val = [];
data.forEach(function (item) {
// 以当前遍历项,的pid,去map对象中找到索引的id
var parent = map[item.pid];
// 好绕啊,如果找到索引,那么说明此项不在顶级当中,那么需要把此项添加到,他对应的父级中
if (parent) {
(parent.children || ( parent.children = [] )).push(item);
} else {
//如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中,作为顶级
val.push(item);
}
});
return val;
}
console.log(toTree(data))

二、

const data = [
{ id:1,name:'Job',pid:0 },
{ id:2,name:'July',pid:1 },
{ id:3,name:'Mike',pid:2 },
{ id:4,name:'Mob',pid:0 },
{ id:5,name:'Hanle',pid:4 }
]

const createTree = list =>{
const root = [];
const b = {};
list.map(item =>{
const obj = { id:item.id,name:item.name }
b[item.id] = obj
if(!item.pid){
root.push(obj)
}
})
const addChildren = item => {
const parent = b[item.pid]
if(!parent){
return
}
const obj = b[item.id]
parent.children || (parent.children = [])
parent.children.includes(obj) || parent.children.push(obj)
parent.pid && addChildren(parent)
}
data.map(addChildren)
return root ;
}
console.log(createTree(data))

猜你喜欢

转载自www.cnblogs.com/jiadaxiadedaimashenghuo/p/12462128.html
今日推荐