Home > front end >  How to iterate over an array of variables and get the field name for each?
How to iterate over an array of variables and get the field name for each?

Time:10-15

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

CodePudding user response:

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

CodePudding user response:

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

  • Related