How to use Object.fromEntries() with Enum In Typescript
Object.fromEntries() method can generate an array of key-value pairs from enum values for desired representation.
Syntax:
enum TransformEnum {
Value1 = 'VALUE1',
Value2 = 'VALUE2',
}
// Transform Object
const transformedObj = Object.fromEntries(
Object.values(TransformEnum).map((v) => [v, transformFunction(v)])
);
Example: The following code shows how the Object.fromEntries() method can be used with Enum to map enum to object in TypeScript.
enum Game {
P = 'PLAYING',
PS = 'PAUSED',
F = 'FINISHED',
}
const gameObj = Object.fromEntries(
Object.values(Game).map((v) =>
[v, v.toLowerCase()])
);
console.log(gameObj);
Output:
{
PLAYING: 'playing',
PAUSED: 'paused',
FINISHED: 'finished'
}
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