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

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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