TypeScript enum to object array

前端 未结 15 2920
不思量自难忘°
不思量自难忘° 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:09

    I didn't like any of the above answers because none of them correctly handle the mixture of strings/numbers that can be values in TypeScript enums.

    The following function follows the semantics of TypeScript enums to give a proper Map of keys to values. From there, getting an array of objects or just the keys or just the values is trivial.

    /**
     * Converts the given enum to a map of the keys to the values.
     * @param enumeration The enum to convert to a map.
     */
    function enumToMap(enumeration: any): Map {
      const map = new Map();
      for (let key in enumeration) {
          //TypeScript does not allow enum keys to be numeric
          if (!isNaN(Number(key))) continue;
    
          const val = enumeration[key] as string | number;
    
          //TypeScript does not allow enum value to be null or undefined
          if (val !== undefined && val !== null)
              map.set(key, val);
      }
    
      return map;
    }
    

    Example Usage:

    enum Dog {
        Rover = 1,
        Lassie = "Collie",
        Fido = 3,
        Cody = "Mutt",
    }
    
    let map = enumToMap(Dog); //Map of keys to values
    
    lets objs = Array.from(map.entries()).map(m => ({id: m[1], name: m[0]})); //Objects as asked for in OP
    let entries = Array.from(map.entries()); //Array of each entry
    let keys = Array.from(map.keys()); //An array of keys
    let values = Array.from(map.values()); //An array of values
    

    I'll also point out that the OP is thinking of enums backwards. The "key" in the enum is technically on the left hand side and the value is on the right hand side. TypeScript allows you to repeat the values on the RHS as much as you'd like.

提交回复
热议问题