How to useObject.values() and map() in Typescript

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.

Example: In this example we are using Object.values() to extract enum values, then map() transforms each value into an object with both label and value properties, creating an array representing enum values.

JavaScript
enum Color {
    Red = 'RED',
    Green = 'GREEN',
    Blue = 'BLUE',
}

const colorArrayValuesMap = Object.values(Color)
    .map(value => ({ label: value, value }));

console.log(colorArrayValuesMap);

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....