Aquí hay una muestra de árbol obtenida a través de 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", }, }, }, ];Quiero generar una matriz simple de todos los padres del objeto de árbol como este:
const output = [ { id: "2", name: "Father", }, { id: "3", name: "Grand Father", } ]Esta es mi función recursiva:
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(); ¿Hay una mejor manera de generar la matriz? Uso la biblioteca lodash, ¿funcionaría algo como _.flatMapDeep ?
Hay algunas optimizaciones menores posibles:
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]));