大家好!我叫戴向天
QQ群:602504799
如若有不理解的,可加QQ群进行咨询了解
const data = [
{pid:1,id:2,name:'一级'},
{pid:2,id:3,name:'二级'},
{pid:3,id:4,name:'三级'},
{pid:4,id:5,name:'四级'},
{pid:4,id:6,name:'五级'},
{pid:4,id:7,name:'六级'},
];
const data2 = [
{parentId:1,id:2,name:'一级'},
{parentId:2,id:3,name:'二级'},
{parentId:3,id:4,name:'三级'},
{parentId:4,id:5,name:'四级'},
{parentId:4,id:6,name:'五级'},
{parentId:4,id:7,name:'六级'},
];
function arrayToTree(array,paramsKey){
// pid 和id 都是字符串
const pid = paramsKey.pid;
const id = paramsKey.id;
let copyArr = JSON.parse(JSON.stringify(array));
// 筛选出没有父级的数据
array.forEach(function(item){
copyArr = copyArr.filter(function(child){
return child[pid] !== item[id]
})
})
// 递归转换
function treeLoop(arr = [],total=[]){
for(let i=0;i<arr.length;i++){
const aid = arr[i][id]
let children = total.filter(function(child){
return child[pid] === aid
});
if(children.length > 0){
children = treeLoop(children,total);
}
arr[i].children = children;
}
return arr;
}
return treeLoop(copyArr,array)
}
// 使用方法
arrayToTree(data,{pid:'pid',id:'id'})
arrayToTree(data,{pid:'parentId',id:'id'})