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 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 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 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 ContentUsing JSON.stringifyUsing fast-json-st
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 ContentUsing JSON.stringify()Using json-stringify-safe libraryUsing a Custom Serialization FunctionUsing
5 min read
How to Convert a String to enum in TypeScript? In TypeScript, an enum is a type of class that is mainly used to store the constant variables with numerical and string-type values. In this article, we will learn, how we can convert a string into an enum using TypeScript.These are the two approaches that can be used to solve it:Table of ContentUsi
5 min read
How to Iterate over Enum Values in TypeScript? Enums in TypeScript are a way to define a set of named constants. Sometimes we may need to iterate over all the values of an enum. There are several approaches to iterate over the enum values in TypeScript which are as follows: Table of Content Using a for...in loopUsing Object.values()Using a forâ¦o
2 min read
How to Declare Specific Type of Keys in an Object in TypeScript ? In TypeScript, object definitions can include specific key-value types using index signatures. You can declare specific types of keys in an object by using different methods as listed below:Table of ContentUsing Mapped TypesUsing InterfaceUsing Inline Mapped Types with typeUsing Record Utility TypeU
3 min read
How to Iterate Over Object Properties in TypeScript In TypeScript, Objects are the fundamental data structures that use key-value pair structures to store the data efficiently. To iterate over them is a common task for manipulating or accessing the stored data. TypeScript is a superset of JavaScript and provides several ways to iterate over object pr
3 min read
How to Filter Keys of Type string[] in TypeScript ? In TypeScript, the filtering of keys of type string[] can be done by iterating over the data object, and applying the condition to the string if the key is a string. If the condition is satisfied, then an array of output results is created which consists of filtered keys of type string[]. The below
3 min read