Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

118
Vistas
Looking for a better way to extract all parents from a tree object into a simple array

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

There are some minor optimizations possible:

  • Do not expose output array unnecessarily
  • Just start collection one level deeper
  • Recursion is unnecessary
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]));

Playground

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda