Consider the following enum:
1enum Color {2 Red = "R",3 Green = "G",4 Blue = "B",5}
If you want to loop through the keys of the enum, first retrieve the keys using Object.keys
and then loop through the keys:
1Object.keys(Color).forEach(key => {2 console.log(key) // Red, Green, Blue3})
To loop through the values of the enum, use Object.values
:
1Object.values(Color).forEach(value => {2 console.log(value) // R, G, B3})
When we do not specify the values of the enum, the values are automatically assigned to the keys.
In this case, we can loop through the enum values using Object.keys
and filter out the strings which are not numbers:
1enum Color {2 Red,3 Green,4 Blue,5}67Object.keys(Color)8 .filter(key => isNaN(Number(key)))9 .forEach(key => {10 console.log(key) // Red, Green, Blue11 })
To loop through the enum values, we can use Object.values
and filter out the values which are numbers:
1Object.values(Color)2 .filter(value => typeof value === "number")3 .forEach(value => {4 console.log(value) // 0, 1, 25 })
If you have liked article, stay in touch with me by following me on twitter.
Leave a Comment