js数组和树互转1. 数组转树
const arr = [
{id:1, parentId: null, name: 'a'},
{id:2, parentId: null, name: 'b'},
{id:3, parentId: 1, name: 'c'},
{id:4, parentId: 2, name: 'd'},
{id:5, parentId: 1, name: 'e'},
{id:6, parentId: 3, name: 'f'},
{id:7, parentId: 4, name: 'g'},
{id:8, parentId: 7, name: 'h'},
]
1.1 利⽤map存储数组项,空间换时间
function array2Tree(arr){
if(!Array.isArray(arr) || !arr.length) return;
let map = {};
arr.forEach(item => map[item.id] = item);
let roots = [];
arr.forEach(item => {
const parent = map[item.parentId];
if(parent){
(parent.children || (parent.children=[])).push(item);
}
else{
roots.push(item);
}
})
return roots;
}
1.2 利⽤递归
//需要插⼊⽗节点id,pid为null或'',就是root节点,然后root节点再去⾃⼰的⼦节点
function array2Tree(data, pid){
let res = [];
data.forEach(item => {
if(item.parentId === pid){
let itemChildren = array2Tree(data,item.id);
if(itemChildren.length) item.children = itemChildren;
res.push(item);
}
});
return res;
}
2. 树转数组
2.1 深度优先遍历
function dfs(root,fVisit){
let stack = Array.isArray(root) ? [...root] : [root];
while(stack.length){
let node = stack.pop();
fVisit && fVisit(node);
let children = node.children;
if(children && children.length){
for(let i=children.length-1;i>=0;i--) stack.push(children[i]);
}
}
}
2.2 ⼴度优先遍历
function bfs(root,fVisit){
let queue = Array.isArray(root) ? [...root] : [root];
while(queue.length){
let node = queue.shift();
fVisit && fVisit(node);
let children = node.children;
if(children && children.length){
for(let i=0;i<children.length;i++) queue.push(children[i]);
}
}
}
3. 验证
//验证数组转树
let a = array2Tree(arr,null); console.log(a);
//验证树转数组
js合并两个数组let a1 = [];
bfs(a,node => a1.push(node)); console.log(a1);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。