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

115
Vistas
JS array recursion for unknown number of objects

I have an Object with nested objects in JS and there's an Object with array that has the same name and can pop up multiple times with different values. I just want to sum the length of each array always going one level deeper till this object is missing.

for example:

0 : {id: 1, importantObject: {id: 1, {importantObject: {id: 1, importantObject:{...},}, somethingElse: 23}, something: 'test'}

1 : {id: 2, importantObject: {id: 24, {importantObject: {id: 55, importantObject:{...},}, somethingElse: 92}, something: 'test'}

and so on..

I've tried to do the following:

const getCount = (a) => {
    let count = 0;
    a.map((b) => {
      if (b.importantObject) {
        count += b.importantObject.length;
        getCount(b.importantObject)
      }
    });
     return count;
  }

However, I don't get the correct count. What am I doing wrong?

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

0

when doing recursion you must use recursive call return value

const getCount = (a) => {
  let count = 0;
  for (let b of a) {
    if (b.importantObject) {
      count += b.importantObject.length;
      count += getCount(b.importantObject); // here
    }
  }
  return count;
}
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