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

Answer

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);
  }
});