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