Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

114
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda