How to useObject.entries() in Typescript

Using Object.entries(), we extract key-value pairs from the TypeScript enum and then map over these pairs to create an array of objects.

Example: In this example, The colorArrayEntries is generated by applying Object.entries() to the Color enum, extracting key-value pairs, and mapping them into an array of objects containing the label and value of each color.

Javascript
enum Color {
    Red = 'RED',
    Green = 'GREEN',
    Blue = 'BLUE',
}
const colorArrayEntries = Object.entries(Color)
    .map(([label, value]) => ({ label, value }));
console.log(colorArrayEntries);

Output:

[
  { label: 'Red', value: 'RED' },
  { label: 'Green', value: 'GREEN' },
  { label: 'Blue', value: 'BLUE' }
]

TypeScript Enum to Object Array

TypeScript enums allow us to define or declare a set of named constants i.e. a collection of related values which could either be in the form of a string or number or any other data type. To convert TypeScript enum to object array, we have multiple approaches.

Example:

enum DaysOfWeek {
  Sunday = 'SUN',
  Monday = 'MON',
  Tuesday = 'TUE'
}
After Converting to object arrays
[   { label: 'Sunday', value: 'SUN' },   
    { label: 'Monday', value: 'MON' },   
    { label: 'Tuesday', value: 'TUE' }
]

Below are the approaches used to convert TypeScript enum to object array:

Table of Content

  • Manual Mapping
  • Using Object.entries()
  • Using Object.keys() and map()
  • Using Object.values() and map()

Similar Reads

Approach 1: Manual Mapping

Manually iterate through the enum keys and values, creating an array of objects....

Approach 2: Using Object.entries()

Using Object.entries(), we extract key-value pairs from the TypeScript enum and then map over these pairs to create an array of objects....

Approach 3: Using Object.keys() and map()

This approach involves using Object.keys() to obtain an array of enum keys and then mapping over them to create an array of objects....

Approach 4: Using Object.values() and map()

This method leverages Object.values() to extract enum values, then applies map() to convert each value into an object with label and value properties, generating an array representation of enum values, aiding in various operations....