TypeScript enum to object array

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

    I'm surprised in a TypeScript thread no one gave valid TypeScript function with typing supported. Here's variation of @user8363 solution:

    const isStringNumber = (value: string) => isNaN(Number(value)) === false;
    
    function enumToArray<T extends {}>(givenEnum: T) {
      return (Object.keys(givenEnum).filter(isStringNumber) as (keyof T)[]).map(
        (key) => givenEnum[key]
      );
    }
    
    0 讨论(0)
  • 2020-12-08 04:24

    If you are using ES6

    It will give you value array of the given enum.

    enum Colors {
      WHITE = 0,
      BLACK = 1,
      BLUE = 3
    }
    
    const colorValueArray = Object.values(Colors); //[ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]
    

    You will get colorValueArray like this [ 'WHITE', 'BLACK', 'BLUE', 0, 1, 3 ]. All the keys will be in first half of the array and all the values in second half.

    0 讨论(0)
  • 2020-12-08 04:26
    class EnumHelpers {
    
        static getNamesAndValues<T extends number>(e: any) {
            return EnumHelpers.getNames(e).map(n => ({ name: n, value: e[n] as T }));
        }
    
        static getNames(e: any) {
            return EnumHelpers.getObjValues(e).filter(v => typeof v === 'string') as string[];
        }
    
        static getValues<T extends number>(e: any) {
            return EnumHelpers.getObjValues(e).filter(v => typeof v === 'number') as T[];
        }
    
        static getSelectList<T extends number, U>(e: any, stringConverter: (arg: U) => string) {
            const selectList = new Map<T, string>();
            this.getValues(e).forEach(val => selectList.set(val as T, stringConverter(val as unknown as U)));
            return selectList;
        }
    
        static getSelectListAsArray<T extends number, U>(e: any, stringConverter: (arg: U) => string) {
            return Array.from(this.getSelectList(e, stringConverter), value => ({ value: value[0] as T, presentation: value[1] }));
        }
    
        private static getObjValues(e: any): (number | string)[] {
            return Object.keys(e).map(k => e[k]);
        }
    }
    
    0 讨论(0)
提交回复
热议问题