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:
// Helper
const StringIsNumber = value => isNaN(Number(value)) === false;
// Turn enum into array
function 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",
}