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

161
Visualizações
count the total number of keys from nested objects and arrays

I have a nested object with different types of properties including string, object and array. I used the recursive approach to count the total number of keys (from key1 to key9) in the object, but failed to achieve the correct solution. Example of my code below.

const data = {
  key1: '1',
  key2: '2',
  key3: { key4: '4' },
  key5: [
    {
      key6: '6',
      key7: '7',
    },
    {
      key8: '8',
      key9: '9',
    }
  ]
}

const countKeys = (data) => {
  let count = 0;

  const helper = (data) => {
    for (let value of Object.values(data)) {
      if (typeof value === 'object') {
        helper(value);
      }
      // this line is problematic as it counts each object in the array as key. 
      if (!Array.isArray(value)) count++;
    }
  }
  helper(data)
  return count;
}
console.log(countKeys(data)) // 10, correct answer is 9

I try to wrap my head around for many hours but couldn't get the solution. Can anyone explain me what I'm missing here and supposed to add to make it work?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

For the data provided, there are nine (9) keys. You could use a recursive countKeys(t) and do a type analysis on t's type -

  1. When it's an Object, for all v in Object.values(t), reduce and count one plus the recursive result, countKeys(v)
  2. When it's an Array, for all v in t, sum countKeys(v)
  3. Otherwise t is neither an Object nor an Array, return zero

function countKeys(t) {
  switch (t?.constructor) {
    case Object:                                     // 1
      return Object
        .values(t)
        .reduce((r, v) => r + 1 + countKeys(v), 0)
    case Array:                                      // 2
      return t
        .reduce((r, v) => r + countKeys(v), 0)
    default:                                         // 3
      return 0
  }
}

const data =
  {key1:"1",key2:"2",key3:{key4:"4"},key5:[{key6:"6",key7:"7"},{key8:"8",key9:"9"}]}

console.log(countKeys(data))

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