寻找一种更好的方法将树对象中的所有父对象提取到一个简单数组中



这是一个通过Typeorm获取的树样例:

interface Base {
id: string;
name: string;
parent?: Base;
}
const sample: Base[] = [
{
id: "1",
name: "Son",
parent: {
id: "2",
name: "Father",
parent: {
id: "3",
name: "Grand Father",
},
},
},
];

我想从树对象中生成一个包含所有父对象的简单数组,如下所示:

const output = [
{
id: "2",
name: "Father",
},
{
id: "3",
name: "Grand Father",
}
]
这是我的递归函数:
function collect(obj: Base, output: Base[]) {
if (obj.parent) {
output = collect(obj.parent, output);
}
const { parent, ...rest } = obj;
output.push(rest);
return output;
}
let output = [];
output = collect(sample[0], output);
// Use pop to remove the last element which is the "Son" object.
output.pop();

是否有更好的方法来生成数组?我用lodash库,像_.flatMapDeep这样的东西可以吗?

这里有一些可能的小优化:

  • 不要不必要地暴露输出数组
  • 开始收集更深一层
  • 递归是不必要的
function collect(input: Base) {
const output = []; // Output contained in function
let current = input.parent; // Skips self
while (current != null) { // Loop instead of recursion
const { parent, ...rest } = current;
output.push(rest);
current = current.parent;
}
return output;
};
console.log(collect(sample[0]));

游乐场

最新更新