例如我有以下树:
root: {
a: {
b: null,
c: {
d: null
}
}
e: null
}
我收到的是 { [child]: parent }
的形状:
{
a: 'root',
e: 'root',
b: 'a',
c: 'a',
d: 'c'
}
但我没有收到如上订购的。不过,我愿意。
如果我知道根项目(没有父项)是 root
,我可以使用这个函数:
const recurs = (obj, cb, parent = 'root') => Object.entries(obj)
.filter(([child, childsParent]) => childsParent === parent)
.forEach(([child]) => {
cb(child);
recurs(obj, cb, child);
});
但是因为它是递归的,所以它可以填充内存,因为在一切完成之前父母不会被垃圾收集。有没有更有效的方法来做这种事情?这可以转换为 for 循环吗?
答案 0 :(得分:1)
使用填充在单个线性循环中的查找表:
const edges = {
a: 'root',
e: 'root',
b: 'a',
c: 'a',
d: 'c'
};
const forest = {};
for (const child in edges) {
const parent = edges[child];
forest[parent] ??= {};
forest[child] ??= {};
forest[parent][child] = forest[child];
}
const tree = forest.root;