I have a TypeScript enum defined as follows:
export enum GoalProgressMeasurements {
Percentage = 1,
Numeric_Target = 2,
Completed_Tasks = 3,
Average_Milestone_Progress = 4,
Not_Measured = 5
}
I want to convert this TypeScript enum to array and represent it as an object array from our API like this:
[
{id: 1, name: 'Percentage'},
{id: 2, name: 'Numeric Target'},
{id: 3, name: 'Completed Tasks'},
{id: 4, name: 'Average Milestone Progress'},
{id: 5, name: 'Not Measured'}
]
Is there an easy and native way to do this conversion, or do I need to build a function to cast the enum to both an integer and a string, and then construct the objects into an array?
Manually create an array of objects with the desired format. This approach is straightforward but requires manual updates if the enum changes.
export enum GoalProgressMeasurements {
Percentage = 1,
Numeric_Target = 2,
Completed_Tasks = 3,
Average_Milestone_Progress = 4,
Not_Measured = 5
}
const goalProgressMeasurementsArray = [
{ id: GoalProgressMeasurements.Percentage, name: 'Percentage' },
{ id: GoalProgressMeasurements.Numeric_Target, name: 'Numeric Target' },
{ id: GoalProgressMeasurements.Completed_Tasks, name: 'Completed Tasks' },
{ id: GoalProgressMeasurements.Average_Milestone_Progress, name: 'Average Milestone Progress' },
{ id: GoalProgressMeasurements.Not_Measured, name: 'Not Measured' }
];
Utilize Object.entries to dynamically convert the enum to an array format. This method assumes the enum values are numbers and the keys are strings.
export enum GoalProgressMeasurements {
Percentage = 1,
Numeric_Target = 2,
Completed_Tasks = 3,
Average_Milestone_Progress = 4,
Not_Measured = 5
}
const goalProgressMeasurementsArray = Object.entries(GoalProgressMeasurements)
.filter(([key, value]) => !isNaN(Number(key))) // Filter out the reverse mappings
.map(([key, value]) => ({
id: Number(key),
name: key.replace(/_/g, ' ') // Replace underscores with spaces
}));