List数组根据pid转化为层级关系的多维数组递归
1.一维转多维层级关系方法
function tranListToTreeDataroute(list, rootValue) {
const arr = [];
list.forEach(item => {
if (item.pid === rootValue) {
let children = tranListToTreeDataroute(list, item.id); // 找到之后 就要去找 item 下面有没有子节点
//sort排序
//children = children.sort((a, b) => {
// return +a.sort - +b.sort;
// });
if (children.length) {
item.children = children; // 如果children的长度大于0 说明找到了子节点
}
arr.push(item); // 将内容加入到数组中
}
});
return arr; // 返回新数组
}
2.使用方法
//例如 数组
listArr = [
{id:"1224454",name:'测试1',pid:'0'},
{id:"19994",name:'子测试1',pid:'1224454'},
{id:"2222555",name:'子测试2',pid:'1224454'},
{id:"9999",name:'三级子测试333',pid:'2222555'},
{id:"666",name:'测试1',pid:'0'},
{id:"888",name:'测试1',pid:'0'},
{id:"9999",name:'测试1',pid:'0'}]
//rootValue 为一级的pid
const dataArr = tranListToTreeDataroute(listArr , '0');
//转换为dataArr
[{
id:"1224454",
name:'测试1',
pid:'0',
children:[
{
id:"19994",
name:'子测试1',
pid:'1224454'
},
{
id:"2222555",
name:'子测试2',
pid:'1224454'
children:[
{
id:"9999",
name:'三级子测试333',
pid:'2222555'
}
]
},
]
}, {id:"666",name:'测试1',pid:'0'},
{id:"888",name:'测试1',pid:'0'},
{id:"9999",name:'测试1',pid:'0'}]