将一维数组转为树结构的数据

let allRes = [
{id: 1, title: "公司",expand:true, pid: 0},
{id: 60, title: "总经理",expand:true, pid: 1},
{id: 66, title: "业务1部",expand:true, pid: 1},
{id: 76, title: "总经理助理1", expand:true,pid: 60},
{id: 77, title: "总经理助理2", expand:true,pid: 66},
{id: 63, title: "财务部",expand:true, pid: 1},
{id: 64, title: "会计", expand:true, pid: 63},
{id: 65, title: "出纳",expand:true, pid: 63},
{id: 68, title: "总监",expand:true, pid: 66},
{id: 70, title: "总监", expand:true,pid: 67},
{id: 81, title: "test",expand:true, pid: 67},
{id: 71, title: "业务员",expand:true, pid: 66},
{id: 75, title: "会计员", expand:true, pid: 64}
];



let result = allRes.reduce(function(prev, item) {

prev[item.pid] ? prev[item.pid].push(item) : prev[item.pid] = [item];
return prev;
}, {});
for (let prop in result) {
console.log(result[prop])
result[prop].forEach(function(item, i) {
result[item.id] ? item.children = result[item.id] : ''
});
}

result = result[0];
posted @ 2018-09-06 15:49  红叶1994  阅读(1037)  评论(0编辑  收藏  举报