每日一题(八零)数组转树
作者:互联网
数组转树
将数组形式的数据结构转为树形的数据结构,例如
let arr= [
{id:1,name:'节点1',pid:null},
{id:2,name:'节点2',pid:null},
{id:3,name:'节点3',pid:1},
{id:4,name:'节点4',pid:2},
{id:5,name:'节点5',pid:1},
{id:6,name:'节点6',pid:3},
{id:7,name:'节点7',pid:4},
{id:8,name:'节点8',pid:2},
{id:9,name:'节点9',pid:1},
{id:10,name:'节点10',pid:3},
{id:11,name:'节点11',pid:null}
]
//转化为
{
id:1,
name:'节点1',
children:[
{
id:2,
name:'节点2',
children:[
...
]
}
...
]
}
代码实现:
//将数组对象转换成我们需要的结构,添加children属性
function changeNode(obj){
return {
id:obj.id,
name:obj.name,
pid:obj.pid,
children:[]
}
}
//转换成树
function toTree(arr){
//转换之后的对象
let nodeObj = {};
//结果数组,可能存在多个根节点
let results = [];
arr.forEach(obj=>{
//以树之前的id作为对象的key
nodeObj[obj.id] = changeNode(obj);
})
//遍历新的对象
for(let o in nodeObj){
if(nodeObj[o].pid){
//如果当前对象存在pid则找到他的pid那个对象,然后把当前对象放到他的pid对象里面的children数组中
nodeObj[nodeObj[o].pid].children.push(nodeObj[o]);
}else{
results.push(nodeObj[o]);
}
}
//返回结果数组
return results;
}
树形结构转为数组结构
//方式1
function flat(datas){
let arr = [];
datas.forEach(data=>{
arr.push(data);
if(!Array.isArray(data.children)){
return arr;
}
arr = arr.concat(flat(data.children));
})
return arr;
}
//方式2
function flat(datas){
return datas.reduce((pre,cur)=>{
return pre.concat(cur,Array.isArray(cur.children)?flat(cur.children):[]);
},[])
}
标签:arr,name,pid,节点,children,八零,数组,转树,id 来源: https://blog.csdn.net/MFWSCQ/article/details/111377739