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

177
Visualizações
How to iterate over an array of variables and get the field name for each?

I want to iterate over an array of variables and then push / console.log the variable name of each.

This code is not working as I thought it might.

let firstOne = true;
let secondOne = true;
let thirdOne = false;

let errorArray = [firstOne, secondOne, thirdOne];

errorArray.forEach((element) => {
  if (element == true) {
    console.log((Object.keys({ element })[0]));
  }
});

I was expecting to see firstOne, secondOne in the console.log but instead, it's just 'element'.

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

0

Arrays don't have keys. They use numeric indexes. To get the key, you'll need to use an object. To iterate the object convert it to an array of [key, value] pairs using Object.entries(). When you iterate the array of pairs, use destructuring to get the element and the key.

let firstOne = true;
let secondOne = true;
let thirdOne = false;

let errorArray = Object.entries({ firstOne, secondOne, thirdOne });

errorArray.forEach(([key, element]) => {
  if (element) {
    console.log(key);
  }
});

about 4 years ago · Juan Pablo Isaza Relatório

0

This is very similar to another answer but slightly different syntax but the concept remains to convert the object into an array and iterate over it as a key/value pair.

let firstOne = true;
let secondOne = true;
let thirdOne = false;

let errorObjs = {
  firstOne,
  secondOne,
  thirdOne
};

for (const [key, value] of Object.entries(errorObjs)) {
  if (value) {
    console.log(`${key}: ${value}`);
  }
}

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