将以上扁平数组转为树形数组
// 查找一级分类
let cate_1st = data.filter((item) => item.pId == 0);
// 递归
function convert(arr, origin) {
return arr.map((parent) => {
let children = origin.filter((child) => parent.id === child.pId);
if (children.length) {
return { ...parent, children: convert(children, origin) };
} else {
return { ...parent };
}
});
}
let treeData = convert(cate_1st, data);
将树形数组拉平为扁平数组
function flat(arr){
var newArr=[];//申请新数组
for(var i=0;i<arr.length;i++){
if(arr<i>.childrens){//childrens存在
newArr.push(...flat(arr[i].childrens));
//递归,调用flat方法,并将返回结果push到新数组
delete arr[i].childrens;//删除原有的childrens属性
}
newArr.push({...arr[i]});//三个点,展开对象,push新对象
}
return newArr;//返回数组
}