I have a string enum and need to get all the values. For instance, for the below enum, I'd like to return ["Red", "Yellow"]
:
export enum FruitColors {
Apple = "Red",
Banana = "Yellow",
}
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
There are two ways to convert an Enum to String in Java, first by using the name() method of Enum which is an implicit method and available to all Enum, and second by using toString() method.
valueOf. Returns the enum constant of the specified enum type with the specified name. The name must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.)
You're looking for Object.values()
According to this GitHub comment, this can be achieved the following way:
Object.keys(FruitColors).map(c => FruitColors[c]);
You can inspect the FruitColors
object. Note that if you do not assign names for the enum values, the generated code will be different and a simple key/value based mapping will lead to wrong results. e.g.
export enum FruitColors {
"Red",
"Yellow",
}
Object.values(FruitColors); // ["Red", "Yellow", 0, 1]
Because the generated code is along these lines:
var FruitColors;
(function (FruitColors) {
FruitColors[FruitColors["Red"] = 0] = "Red";
FruitColors[FruitColors["Yellow"] = 1] = "Yellow";
})(FruitColors = exports.FruitColors || (exports.FruitColors = {}));
You could then just filter the results by typeof value == "string"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With