![]() |
Mapping enum or tuple values to objects is a common practice in TypeScript for handling different data representations. This article explores various methods to map enumerations (enums) and tuples to objects, providing examples to illustrate each method. Table of Content Manually mapping Enum to ObjectConsequently, treating enum members as object keys has a one-to-one relationship with their corresponding values. Syntax:// Enum
enum Name {
Value1 = 'VALUE1',
Value2 = 'VALUE2',
}
// Object
const obj: Record<Name, ValueType> = {
[Name.Value1]: 'correspondingValue1',
[Name.Value2]: 'correspondingValue2',
};
Example: The below code maps a enum to a JavaScript object.
Output: Flavor Codes: {
STRAWBERRY: 'FF0000',
MINT: '00FF00',
BLUEBERRY: '0000FF'
}
Manually mapping tuple to objectTuple indexes can be easily mapped by using object keys. Syntax:type Type = [Type1, Type2];
// Object with Tuple
const objWithTuple: Record<string, Type> = {
k1: [v1, v2],
k2: [v3, v4],
};
Example: The below code will map the tuple to an JavaScript object.
Output: {
"o": [0, 0],
"e": [10, 20]
}
Using Object.fromEntries() with EnumObject.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.
Output: {
PLAYING: 'playing',
PAUSED: 'paused',
FINISHED: 'finished'
}
Mapping Tuple to Object with ReduceWhile building an object step by step, reduce() function is applied to change or map tuple value into custom keys depending on certain rules defined within reduce operation. Syntax:type T = [T1, T2];
const a: T[] = [
[v1, v2],
[v3, v4],
];
const r = a.reduce((acc, [k, v]) => {
acc[k] = v;
return acc;
}, {} as Record<string, V>);
Example: The below code maps a tuple to object using the reduce() method.
Output: {
Laptop: 1200,
Headphones: 150
} Using for…in with EnumYou 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.
Output: {
"Apple": "apple",
"Orange": "orange",
"Banana": "banana"
} |
Reffered: https://www.geeksforgeeks.org
Geeks Premier League |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |