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 sort (arr) {
var newArr = [];
var conts = [];
// 计数
for (let i = 0; i < arr.length; i++) {
var val = arr[i];
if(!conts[val.pid]){
conts[val.pid] = [];
}
conts[val.pid].push(val);
}
// console.log(conts);
// 排序
for (let j = 0; j < arr.length; j++) {
var val = arr[j];
if(conts[j]){
val.children = conts[j];
}
if(val.pid === 0){
newArr.push(val);
}
}
return newArr;
}
var a = sort(arr);
console.log(a);
console