-1

I have created this enum:

export enum MyEnum {
    VALUE1 = 'brown',
    VALUE2 = 'green'
}

I would like to iterate over the enum for the purposes of building a select menu with the key being the value and the string being the label. But this code:

for (const key in Object.keys(MyEnum)) {
  console.log('value is');
  console.log((MyEnum as any)[key]);
}

produces an "undefined" when I try and look up an enum value by key. What's the proper way to get the enum value by its key?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Dave
  • 15,639
  • 133
  • 442
  • 830
  • Is this a typo? Did you really intend to write `in Object.keys(MyEnum)` (keys of the keys?) instead of `of Object.keys(MyEnum)` or perhaps `in MyEnum`? – jcalz Mar 10 '23 at 18:01
  • Or as you want both `for (const [key, value] of Object.entries(MyEnum)) { }`. Specific problem is you're iterating over the _indexes_, https://stackoverflow.com/q/3010840/3001761 shows how to actually iterate over array values, but really you're just starting with an object `{ VALUE1: "brown", VALUE2: "green" }`, so maybe https://stackoverflow.com/q/2958841/3001761. – jonrsharpe Mar 10 '23 at 18:06

1 Answers1

1

use of instead of in:

typescript playground link

enum MyEnum {
    VALUE1 = 'brown',
    VALUE2 = 'green'
}

for (const key of Object.keys(MyEnum)) {
  console.log('value is');
  console.log((MyEnum as any)[key]);
}

As an aside, you can do

type MyEnumKey = keyof typeof MyEnum
for (const key of (Object.keys(MyEnum) as MyEnumKey[])) {
  console.log('value is');
  console.log(MyEnum[key]);
}
Chance
  • 11,043
  • 8
  • 61
  • 84