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

306
Visualizações
How can I loop over an array of objects without Object.keys()?

I'm a beginner at JavaScript and I'm trying to solve this problem without Object.keys() or any regex. I have a working solution but I'm wondering if there's a better way to call on the object key within the array while still looping. If anyone has a way to do this that's basic please let me know.

Problem: Create a function called keyCount which accepts two parameters, an array of objects, and a string. The function should return a number which is the number of times that key appears in the array of objects.

Expected Result: countTimesOfKey([{name:"Sharon"}, {name: "Manish"},{lastName: "Terma"}], "name")) // 2

My Answer:

function countTimesOfKey(arr, str) {
  let count = 0

  for (let i in arr){
    let test = arr[i]
    let test2 = test[str]

   if (test2 !== undefined){
      count += 1
    }
  }
  return count
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You can use Array.filter to filter out the items in the array which have str as a property (by using Object.hasOwnProperty), then return the length of the resulting array:

function countTimesOfKey(arr, str) {
  return arr.filter(e => e.hasOwnProperty(str)).length;
}

console.log(countTimesOfKey([{
  name: "Sharon"
}, {
  name: "Manish"
}, {
  lastName: "Terma"
}], "name"))

about 4 years ago · Juan Pablo Isaza Relatório

0

Of course, using Object.keys() and @Spectric's solution are way better than the one below, I just wanted to show that we can even more 'simplify' this.


We can use for...in to

  • Loop over each object in the array
  • Loop over each key of the object on the current index
    • Compare the name of each key against our check variable
      • Increase our counter
  • return the result counter

const result = countTimesOfKey([{name:"Sharon"}, {name: "Manish"},{lastName: "Terma"}], "name");
console.log(result);

function countTimesOfKey(arr, name) {
    let counter = 0;
    for (a in arr) {
        for (let k in arr[a]) {
            if (k === name) {
                counter++;
            }
        }
    }
    return counter;
}

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