直接上代码
var data = [{
id: 1,
name: "办公管理",
pid: 0,
children: [{
id: 2,
name: "请假申请",
pid: 1,
children: [
{ id: 4, name: "请假记录", pid: 2 },
],
},
{ id: 3, name: "出差申请", pid: 1 },
]
},
{
id: 5,
name: "系统设置",
pid: 0,
children: [{
id: 6,
name: "权限管理",
pid: 5,
children: [
{ id: 7, name: "用户角色", pid: 6 },
{ id: 8, name: "菜单设置", pid: 6 },
]
}, ]
},
];
1.0:将树形结构处理为扁平数组
const arr = data.reduce(function(pre,item){
const callee = arguments.callee //将运行函数赋值给一个变量备用
pre.push(item)
if(item.children && item.children.length > 0) item.children.reduce(callee,pre); //判断当前参数中是否存在children,有则递归处理
return pre;
},[]).map((item) => {
item.children = []
return item
})
console.log(arr)
2.0:将扁平数组处理为树形结构
let result = arr.reduce(function(prev, item) {
prev[item.pid] ? prev[item.pid].push(item) : prev[item.pid] = [item];
return prev;
}, {});
console.log(result)
for (let prop in result) {
result[prop].forEach(function(item, i) {
result[item.id] ? item.children = result[item.id] : ''
});
}
result = result[0];
console.log(result)
网友评论