Here's a tree sample fetched via 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",
},
},
},
];
I want to generate a simple array of all parents from the tree object like this:
const output = [
{
id: "2",
name: "Father",
},
{
id: "3",
name: "Grand Father",
}
]
This is my recursive function:
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();
Is there a better way to generate the array? I use the lodash library, would something like _.flatMapDeep work?
There are some minor optimizations possible:
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]));