Since the project is going to have a sunburst chart, because the backend only helps me extract the flattened array of objects in the database, I need to process the data. For this, I have to deal with the data. The following is my data processing process.
// 本算法在不确定顶级节点的情况下,优先过滤出顶级节点,在进行遍历
// 进行数据的大量缓存,用空间换时间,让生成tree的速度像柔丝般顺滑
function generatorTree(data) {
const value = 'value';
const name = 'name';
const id = 'id';
const pid = 'pid';
// 保存所有ID,然后找到pid没有对应节点的就是顶级节点
const hasId = {};
// 顶层父节点数组
const topPIdArr = [];
// 将每个节点对应的子节点对应起来
const nodeToChildren = {};
// 获取所有父ID(包括顶级节点的父ID)
const pidSet = new Set();
data.forEach(e => {
// 之后通过topPIdArr数组可以通过深度遍历生成父子节点tree
if (nodeToChildren[e[pid]]) {
nodeToChildren[e[pid]].push({name: e[name], value: e[value], id: e[id], children: []})
} else {
nodeToChildren[e[pid]] = [{name: e[name], value: e[value], id: e[id], children: []}];
}
pidSet.add(e[pid]);
hasId[e[id]] = true;
});
// 遍历父ID集合
for (const pid of pidSet) {
if (!hasId[pid]) {
// 如果idObj没有该pid节点,说明它是顶级父节点
topPIdArr.push(pid);
}
}
// 如果你不想改变nodeToChildren,建议深拷贝一下,当然里面如果属性有undefined,函数或者symbol那你得自己实现一个深拷贝方法
const copyNodeToChildren = JSON.parse(JSON.stringify(nodeToChildren));
// 用来存储生成的树状结构数据
const nodeTree = [];
// 找到所有顶级节点,开始递归生成tree,tree,tree,真的脆
data.filter(e => topPIdArr.includes(e.pid)).forEach((e, index) => {
nodeTree.push({name: e[name], value: e[value], id: e[id], children: []});
deepCreateTree(nodeTree[index].id, nodeTree[index].children);
});
// 通过深度优先遍历的思路,生成父子Tree
function deepCreateTree (id, children) {
// 存在的话,说明该id的节点存在子节点
if (copyNodeToChildren[id]) {
// 将数据推进对应id节点的children中
children.push(...copyNodeToChildren[id]);
copyNodeToChildren[id].forEach(e => {
deepCreateTree(e.id, e.children);
});
}
}
console.log(nodeTree, 847587)
}
generatorTree([
{id: 1, value: 2, name: 'A', pid: 0},
{id: 2, value: 2, name:'B', pid: 1},
{id: 3, value: 2, name:'C', pid: 2},
{id: 4, value: 2, name:'D', pid: 3},
{id: 5, value: 2, name:'E', pid: 0}
]);
If you like my implementation, you can share it with the link below, thank you
https://www.cnblogs.com/smallZoro/p/12695978.html