const list = [
{ id:1,pid:0,value:"莫林莲" },
{ id:2,pid:1,value:"莫林莲1" },
{ id:3,pid:1,value:"莫林莲2" },
{ id:4,pid:1,value:"莫林莲3" },
{ id:5,pid:0,value:"廖天" },
{ id:6,pid:5,value:"廖天1" },
{ id:7,pid:5,value:"廖天2" },
{ id:8,pid:5,value:"廖天3" },
{ id:9,pid:0,value:"彭勇" },
{ id:10,pid:9,value:"彭勇1" },
{ id:11,pid:10,value:"彭勇2" },
{ id:12,pid:11,value:"彭勇3" },
{ id:13,pid:12,value:"彭勇4" },
{ id:14,pid:13,value:"彭勇5" },
{ id:15,pid:14,value:"彭勇6" },
{ id:16,pid:0,value:"陳林" }
];
const data = (()=>{
let arr = [];
function toTree(id,array,list){
let newArr = list.filter(item=> item.pid === id );
newArr.forEach(item=>{
let arr = [];
item.children = toTree(item.id,arr,list);
array.push(item);
});
return array;
}
toTree(0,arr,list);
console.log(arr);
return arr;
})();
生成的数据
[{
"id": 1,
"pid": 0,
"value": "莫林莲",
"children": [{
"id": 2,
"pid": 1,
"value": "莫林莲1",
"children": []
}, {
"id": 3,
"pid": 1,
"value": "莫林莲2",
"children": []
}, {
"id": 4,
"pid": 1,
"value": "莫林莲3",
"children": []
}]
}, {
"id": 5,
"pid": 0,
"value": "廖天",
"children": [{
"id": 6,
"pid": 5,
"value": "廖天1",
"children": []
}, {
"id": 7,
"pid": 5,
"value": "廖天2",
"children": []
}, {
"id": 8,
"pid": 5,
"value": "廖天3",
"children": []
}]
}, {
"id": 9,
"pid": 0,
"value": "彭勇",
"children": [{
"id": 10,
"pid": 9,
"value": "彭勇1",
"children": [{
"id": 11,
"pid": 10,
"value": "彭勇2",
"children": [{
"id": 12,
"pid": 11,
"value": "彭勇3",
"children": [{
"id": 13,
"pid": 12,
"value": "彭勇4",
"children": [{
"id": 14,
"pid": 13,
"value": "彭勇5",
"children": [{
"id": 15,
"pid": 14,
"value": "彭勇6",
"children": []
}]
}]
}]
}]
}]
}]
}, {
"id": 16,
"pid": 0,
"value": "陳林",
"children": []
}]
js 树结构转 pid 格式
https://www.jianshu.com/p/3efcdf0ac826