根据id,pid生成树结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
let Arr = [
{
label: '父节点',
id:1,
pid:null
},
{
label: '父节点',
id:2,
pid:null
},
{
label: '父节点',
id:3,
pid:null
},
{
label: '父节点',
id:4,
pid:null
},
{
label: '父节点',
id:5,
pid:null
},
{
label: '父节点',
id:6,
pid:null
},
{
label: '父节点',
id:7,
pid:1
},
{
label: '父节点',
id:8,
pid:1
},
{
label: '父节点',
id:9,
pid:2
},
{
label: '父节点',
id:10,
pid:3
},
{
label: '父节点',
id:11,
pid:10
},
{
label: '父节点',
id:12,
pid:11
}
];
Array.prototype.toTree = function(id){
let tree = [];
for(let i=0;i<this.length;i++){
if(this[i].pid == id){
this[i].children = this.toTree(this[i].id);
tree.push(this[i]);
}
}
return tree;
}
let tree = Arr.toTree(null);
console.log(tree);
</script>