Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to Check the Type of an Object in Typescript ?
Next article icon

How to map Enum/Tuple to Object in TypeScript ?

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Object
  • Manually mapping tuple to object
  • Using Object.fromEntries() with Enum
  • Mapping Tuple to Object with Reduce
  • Using for...in with Enum

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

Next Article
How to Check the Type of an Object in Typescript ?

B

bytebarde55
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Geeks Premier League
  • TypeScript
  • Geeks Premier League 2023

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences