I'm working with some enums to ensure the typing for my models. But now, I needed to create a select box with that. I'll explain how to do that.
Considering a key/value enum, you can use the Object.entries to extract the data and create the array.
export enum EventModel {
REPAIR = "Repair",
PREVENT = "Prevent",
}
export const EventModelList: {
key: string;
value: string;
}[] = Object.entries(EventModel)
.map(([key, value]) => ({ key, value }));
So cool... but, if you have an enum without key=value association?
In this case, you need to get the values and filter only strings:
export enum OtherModel {
MODEL_A,
MODEL_B
}
export const OtherModelList: {
value: string;
}[] = Object.values(OtherModel)
.filter((value) => typeof value === "string")
.map((value) => ({ value: value as string }));
It was necessary because each value without an association generates two values: the key itself and the value (a number).
I created a simple sandbox to test that: codesandbox:ts-enum-as-array
Top comments (0)