TypeScript enum to object array TypeScript enum to object array arrays arrays

TypeScript enum to object array


A tricky bit is that TypeScript will 'double' map the enum in the emitted object, so it can be accessed both by key and value.

enum MyEnum {    Part1 = 0,    Part2 = 1}

will be emitted as

{   Part1: 0,   Part2: 1,   0: 'Part1',   1: 'Part2'}

So you should filter the object first before mapping. So @Diullei 's solution has the right answer. Here is my implementation:

// Helperconst StringIsNumber = value => isNaN(Number(value)) === false;// Turn enum into arrayfunction ToArray(enumme) {    return Object.keys(enumme)        .filter(StringIsNumber)        .map(key => enumme[key]);}

Use it like this:

export enum GoalProgressMeasurements {    Percentage,    Numeric_Target,    Completed_Tasks,    Average_Milestone_Progress,    Not_Measured}console.log(ToArray(GoalProgressMeasurements));


If you are using ES8

For this case only it will work perfectly fine. 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.

Even this kind of enum will work fine

enum Operation {    READ,    WRITE,    EXECUTE}

But this solution will not work for Heterogeneous enums like this

enum BooleanLikeHeterogeneousEnum {  No = 0,  Yes = "YES",}


Enums are real objects that exist at runtime. So you are able to reverse the mapping doing something like this:

let value = GoalProgressMeasurements.Not_Measured;console.log(GoalProgressMeasurements[value]);// => Not_Measured

Based on that you can use the following code:

export enum GoalProgressMeasurements {    Percentage = 1,    Numeric_Target = 2,    Completed_Tasks = 3,    Average_Milestone_Progress = 4,    Not_Measured = 5}let map: {id: number; name: string}[] = [];for(var n in GoalProgressMeasurements) {    if (typeof GoalProgressMeasurements[n] === 'number') {        map.push({id: <any>GoalProgressMeasurements[n], name: n});    }}console.log(map);

Reference: https://www.typescriptlang.org/docs/handbook/enums.html