一:数组转化为树形结构
1.题干
arr= [{
id: 1,
pid: 0
}, {
id: 2,
pid: 1
}, {
id: 3,
pid: 2
},
{
id: 4,
pid: 1
}]
转换为:
[{
id: 1,
pid: 0,
children: [{
id: 2,
pid: 1,
children: [{
id: 3,
pid: 1,
}]
},
{
id: 4,
pid: 1,
children: []
}]
}]
2.实现
let arr= [{
id: 1,
pid: 0
}, {
id: 2,
pid: 1
}, {
id: 3,
pid: 2
},
{
id: 4,
pid: 1
}]
function arrToTree(arr) {
let result = []
if(!Array.isArray(arr)) { //判断arr是不是数组
return result
}
arr.forEach(item => {
delete item.children;
});
let map = {};
arr.forEach(item => { //建立每个数组元素id和该对象的关系
map[item.id] = item; //可以理解为浅拷贝
});
arr.forEach(item => {
let parent = map[item.pid]; //找到arr中每一项item的父节点
if(parent) {//说明元素有父节点,把元素放在父节点的children下面
(parent.children || (parent.children = [])).push(item);
} else {//说明元素没有父节点,是根节点,把节点push到最终结果中
result.push(item);//item是对象的引用
}
});
return result;//数组里的对象和arr是共享的
}
console.log(arrToTree(arr))
console.log(...arrToTree(arr))

image.png
二:树形结构转化为数组
let tree = {
id: 1,
pid: 0,
children: [{
id: 2,
pid: 1,
children: [{
id: 3,
pid: 1,
}]
},
{
id: 4,
pid: 1,
children: []
}]
};
function treeToArr(tree){
let queue = [tree];
let data =[]; //返回数组
while(queue .length !==0){ //队列为空跳出循环
let item = queue.shift();//取出队列的第一个元素
data.push({
id:item.id,
pid:item.pid
});
let children = item.children; //取出当前节点的子节点
if(children){
for(let i=0;i<children.length;i++){
queue.push(children[i]);//将子节点加入到队列中
}
}
}
return data;
}
console.log(treeToArr(tree))

image.png