<script>
let company = [
{id:1,name:'巴黎圣日尔曼',pid:0},
{id:2,name:'球员部',pid:1},
{id:3,name:'研发部',pid:1},
{id:4,name:'球员一部',pid:2},
{id:5,name:'球员二部',pid:3},
]
function toTree(arr,pid){
const map = arr.reduce((newArr,element)=>{
// console.log('prev',element);
//这里是浅拷贝,会修改原数组,当后续再使用原数组会出现问题
// prev.push(element)
newArr[element.id] = element
return newArr
},[]);
//定义返回结果数组
let result = [];
//遍历传入的对象
for(let i = 0;i<arr.length;i++){
const item = arr[i]
//当遍历到的对象的pid等于传入的根节点id,说明为根节点,直接push到数组中
if(item.pid === pid){
result.push(item)
continue
}
const parent = map[item.pid]
if(parent){
console.log('parent',parent);
parent.children = parent.children || [] //短路运算符,如果左边的有结果则不再进行下边的计算,如果没有结果则采用右边的结果
parent.children.push(item)
}
}
return result
}
console.log(toTree(company,0));
</script>
扁平化数组转化为树形结构
最新推荐文章于 2024-07-25 09:37:37 发布