How to map Enum/Tuple to Object in TypeScript ?
Last Updated : 18 Jul, 2024
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.
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.
TypeScript enum F { S = 'STRAWBERRY', M = 'MINT', B = 'BLUEBERRY', } const FC: Record<F, string> = { [F.S]: 'FF0000', [F.M]: '00FF00', [F.B]: '0000FF', }; console.log("Flavor Codes:", 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.
TypeScript type Point = [number, number]; const pointObj: Record<string, Point> = { 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.
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' }
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.
TypeScript type I = [string, number]; const arr: I[] = [ ['Laptop', 1200], ['Headphones', 150], ]; const obj = arr.reduce((acc, [item, price]) => { acc[item] = price; return acc; }, {} as Record<string, number>); 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.
TypeScript 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" }
Similar Reads
How to Deep Merge Two Objects in TypeScript ?
Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore vario
5 min read
How to Check the Type of an Object in Typescript ?
When working with TypeScript, understanding how to check the type of an object is crucial for ensuring type safety and maintaining code integrity. TypeScript, being a statically typed superset of JavaScript, provides several approaches to accomplish this task as listed below. Table of Content Using
3 min read
How to Cast Object to Interface in TypeScript ?
In TypeScript, sometimes you need to cast an object into an interface to perform some tasks. There are many ways available in TypeScript that can be used to cast an object into an interface as listed below: Table of Content Using the angle bracket syntaxUsing the as keywordUsing the spread operatorU
3 min read
How to Exclude Property from Type in TypeScript ?
In Typescript, sometimes we need to exclude a property from a type when we want a similar type with some properties excluded or if we want to remove a property from the type. There are several approaches to exclude properties from a type in typescript: Table of Content Using Mapped Types with condit
4 min read
How to Create an Object in TypeScript?
TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data. Creating Objects in TypescriptNow, let
4 min read
How to Iterate Array of Objects in TypeScript ?
In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for...of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows: Table of Content Using for..
4 min read
How to Setup a TypeScript Project?
In the world of modern web development, TypeScript has emerged as a powerful superset of JavaScript, offering static typing and improved tooling. Its strong typing system helps developers catch errors early during development, leading to more maintainable and scalable code. Whether you're starting a
2 min read
How to Convert Map to JSON in TypeScript ?
In TypeScript, we can convert the Map to JSON by manipulating the key-value pairs of the Map into JSON-formatted string. We can use various approaches like JSON.stringify, fast-json-stringify, and json-stringify-safe Libraries for the conversion. Table of Content Using JSON.stringifyUsing fast-json-
5 min read
How to Convert an Object to a JSON String in Typescript ?
In TypeScript, an object is a collection of related data and functionality. Objects are made up of properties and methods. Properties describe the object, methods describe what it can do. Table of Content Using JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsi
5 min read
How to Sort or Reduce an Object by Key in TypeScript ?
Sorting an object by key generally refers to arranging its properties in a specific order, while reducing involves selecting a subset of properties based on provided keys. Different approaches allow developers to perform these operations with flexibility. Below are the approaches used to sort or red
3 min read