TypeScript enum to object array

前端 未结 15 2908
不思量自难忘°
不思量自难忘° 2020-12-08 03:38

I have an enum defined this way:

export enum GoalProgressMeasurements {
    Percentage = 1,
    Numeric_Target = 2,
    Completed_Tasks = 3,
    Average_Mile         


        
15条回答
  •  臣服心动
    2020-12-08 04:16

    Easy Solution. You can use the following function to convert your Enum to an array of objects.

     buildGoalProgressMeasurementsArray(): Object[] {
    
        return Object.keys(GoalProgressMeasurements)
                  .map(key => ({ id: GoalProgressMeasurements[key], name: key }))
     }
    

    If you needed to strip that underscore off, we could use regex as follows:

    buildGoalProgressMeasurementsArray(): Object[] {
    
        return Object.keys(GoalProgressMeasurements)
                  .map(key => ({ id: GoalProgressMeasurements[key], name: key.replace(/_/g, ' ') }))
     }
    

提交回复
热议问题