背景
开发过程中遇到后台返回的平铺数据,需要自己根据数据的parent_id将其构造成一套树结构,首先采用递归的方式对数据进行组装。
但后续使用中发现,如果遇到数据量较大(40000+)后,该方法的处理耗时明显过长,且导致页面有较长时间的卡顿,严重影响用户使用。故考虑对算法进行优化。
代码
// 旧版构造树方法-递归
export const buildTree = (node, nodes) => {
// 找到该节点的子节点集
const children = nodes.filter((item) => node.id === item.parent_id);
if(children.length) {
node.children = children;
for (const child of children) {
// 递归
buildTree(child, nodes);
}
}
}
// 新版构造树方法-map
export const newBuildTree = (nodes) => {
const map = {}; // 用于存储每个节点的引用
const roots = []; // 根节点数组-用于存储处理好的树
// 构建节点
nodes.forEach(item => {
map[item.id] = {...item, children: null, label: item.name};
})
// 连接节点
Object.values(map).forEach(node => {
// 遍历节点
if (node.parent_id && map[node.parent_id]) {
// 当该节点存在父节点 map中将该节点存入其父节点的children数组
map[node.parent_id].children ? map[node.parent_id].children.push(node) : map[node.parent_id].children = [node];
} else {
// 当不存在父节点时,已在最顶层,存储该节点
roots.push(node);
}
})
return roots;
}
原文地址
【个人博客】