How to use for…in with Enum In Typescript
You can iterate over the enum keys using a `for…in` loop and construct an object by manually mapping each enum member to a key-value pair.
Syntax:
for (const key in EnumName) {
if (Object.prototype.hasOwnProperty.call(EnumName, key)) {
const value = EnumName[key as keyof typeof EnumName];
obj[value] = /* corresponding value */;
}
}
Example: In this example maps enum values to lowercase strings using a loop and assigns them to an object. It converts enum values to lowercase for each key-value pair.
enum Fruit {
Apple = 'Apple',
Orange = 'Orange',
Banana = 'Banana',
}
let fruitObj: Record<Fruit, string> = {} as Record<Fruit, string>;
for (const key in Fruit) {
if (Object.prototype.hasOwnProperty.call(Fruit, key)) {
const value = Fruit[key as keyof typeof Fruit];
fruitObj[value] = value.toLowerCase();
}
}
console.log(fruitObj);
Output:
{
"Apple": "apple",
"Orange": "orange",
"Banana": "banana"
}
How to map Enum/Tuple to Object in TypeScript ?
Mapping enum or tuple values to objects is a usual action in TypeScript when working with different data representations. Enumerations (enum) and Tuples are two types of data that can be mapped into objects differently based on the methods below in TypeScript.
Table of Content
- Manually mapping Enum to Object
- Manually mapping tuple to object
- Using Object.fromEntries() with Enum
- Mapping Tuple to Object with Reduce
Contact Us