Open In App

How to map Enum/Tuple to Object in TypeScript ?

Last Updated : 17 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Manually mapping Enum to Object

Consequently, 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.

Javascript
enum F {
    S = 'STRAWBERRY',
    M = 'MINT',
    B = 'BLUEBERRY',
}

const FC: Record&lt;F, string&gt; = {
    [F.S]: 'FF0000',
    [F.M]: '00FF00',
    [F.B]: '0000FF',
};

console.log(&quot;Flavor Codes:&quot;, FC);

Output:

Flavor Codes: {
STRAWBERRY: 'FF0000',
MINT: '00FF00',
BLUEBERRY: '0000FF'
}

Manually mapping tuple to object

Tuple 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.

Javascript
type Point = [number, number];

const pointObj: Record&lt;string, Point&gt; = 
{
    o: [0, 0],
    e: [10, 20],
};

console.log(pointObj);

Output:

{
"o": [0, 0],
"e": [10, 20]
}

Using Object.fromEntries() with Enum

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.

Javascript
enum Game {
  P = 'PLAYING',
  PS = 'PAUSED',
  F = 'FINISHED',
}

const gameObj = Object.fromEntries(
    Object.values(Game).map((v) =&gt; 
    [v, v.toLowerCase()])
);

console.log(gameObj);

Output:

{ 
PLAYING: 'playing',
PAUSED: 'paused',
FINISHED: 'finished'
}

Mapping Tuple to Object with Reduce

While 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.

Javascript
type I = [string, number];

const arr: I[] = [
    ['Laptop', 1200],
    ['Headphones', 150],
];

const obj = arr.reduce((acc, [item, price]) =&gt; 
{
    acc[item] = price;
    return acc;
}, {} as Record&lt;string, number&gt;);

console.log(obj);

Output:

{ 
Laptop: 1200,
Headphones: 150
}

Using for…in with Enum

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.

JavaScript
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"
}


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads