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.
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
}
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
Contact Us