0

I would like to know how I can create a loop that is repeated for each item of the enum and still validate that I am in the correct enum (index)

 for('for each or for in?') {
      if (list.names === enum) {
         console.log(enum)
    }
 }


enum = {
  JAMES: 'James',
  MARCO: 'Marco',
  Jane: 'Jane'
}

This code is just an example of what I would like to do, repeat the loop for each type of enum, then validate that I am in the first, second, etc., and then print the current enum

  for (const newNames in enum) {
    console.log(newNames[enum])
  }
Bussola
  • 59
  • 1
  • 8
  • Does this answer your question? [how-to-get-names-of-enum-entries](https://stackoverflow.com/questions/18111657/how-to-get-names-of-enum-entries) – Lin Du Dec 22 '20 at 11:50
  • Does this answer your question? [Get loop counter/index using for…of syntax in JavaScript](https://stackoverflow.com/questions/10179815/get-loop-counter-index-using-for-of-syntax-in-javascript) – pilchard Dec 22 '20 at 11:57
  • it helped a little, in case it didn’t work to print the enum value, in this case we’ll assume if I’m in the JAMES enum, how am I going to access the value 'James'? – Bussola Dec 22 '20 at 12:00
  • There is no `for each` in JavaScript and `for of` doesn't work on non-iterable objects. That leaves only one option… – Bergi Dec 22 '20 at 12:09
  • 1
    @Bussola It's just an object: `enum[key]` – Bergi Dec 22 '20 at 12:10
  • I understood my friend, I tried to do it as in the publication you sent me but returns undefined, I'll add it to the body of the question for you to see if I did it really the right way. – Bussola Dec 22 '20 at 12:17
  • you have it backwards in your edit it should be `console.log(enum[newNames])` – pilchard Dec 22 '20 at 12:20

2 Answers2

3

Here is a quick snippet showing your options, but the for...in is all you need.

const obj = {
  JAMES: 'James',
  MARCO: 'Marco',
  Jane: 'Jane'
}

// for..in and access the value as normal - obj[key]
for (const key in obj) {
  console.log(`key: ${key}, obj[key]: ${obj[key]}`);
}

// for...of return an iterable of the object using Object.entries()
for (let [key, value] of Object.entries(obj)) {
  console.log(`key: ${key}, value: ${value}`);
}

// for...of turn the iterator into an array into an iterator and also get the indexes
for (let [i, [key, value]] of [...Object.entries(obj)].entries()) {
  console.log(`i: ${i}, key: ${key}, value: ${value}`);
}
pilchard
  • 12,414
  • 5
  • 11
  • 23
0

Is this responding to your question ?

const people = {
  linda: 'linda',
  MARCO: 'joshua',
  james: 'james',
  joshua: 'joshua'
};

Object.entries(people).forEach(person => {
  person[0] === person[1] && console.log(person);
});

output:

Array [ "linda", "linda" ]
Array [ "james", "james" ]
Array [ "joshua", "joshua" ]

You might as well take a look at this thread about filtering objects.

johnnyBoy
  • 115
  • 2
  • 12