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