export function list2Tree(data, parentId, children = "children", depth = 0) {
let res = [];
Array.isArray(data) &&
data.forEach(item => {
if (item.parentId === parentId) {
let itemChildren = list2Tree(data, item.id, children, depth + 1);
if (itemChildren.length) item[children] = itemChildren;
res.push({
...item,
depth
});
}
});
return res;
}
6000条数据时候需要 6350.08ms 多,有没有什么办法从算法层面优化一下的
以下数据结构中,id 代表部门编号,name 是部门名称,parentId 是父部门编号,为 0 代表一级部门,现在要求实现一个 convert 方法,把原始 list 转换成树形结构,parentId 为多少就挂载在该 id 的属性 children 数组下,结构如下:
// 原始 list 如下
// 转换后的结果如下
转换方法如下: