Enums are handy in any programming language, so in this article, I have mentioned how we can get an Enum key by value in Typescript with an example.
Suppose, we have the following Enum in Typescript:
enum Colors {
RED ="Red Color",
BLUE ="Blue Color",
GREEN ="Green Color"
}
Now, if you want to get Enum Key by using value in .ts(typescript), then you can simply use the below code
//get enum key by value
let enumKeySecond = Object.keys(Colors)[Object.values(Colors).indexOf("Blue Color")];
console.log(enumKeySecond); // Red
In the above code, we are simply using Object.values()
method to get an array of the enum's values while indexOf()
method to get the index of the value in the array.
Once, we have the Index of the Enum Value, we can pass this value to Object.Keys() to get Enum key, as shown above.
We can also create our own function
//custom function
function getEnumKeyByEnumValue(myEnum: any, enumValue: number | string): string {
let keys = Object.keys(myEnum).filter((x) => myEnum[x] == enumValue);
return keys.length > 0 ? keys[0] : '';
}
console.log(getEnumKeyByEnumValue(Colors,"Red Color"));
//RED
You can take a look at the fiddle example here: https://jsfiddle.net/jatx25oy/
For Numeric Enums, we can simply pass the Index of the Enum to get the Key
enum Numeric{
Zero,
One,
Two
}
console.log(Numeric[0]); // Zero
console.log(Numeric[1]); // One
console.log(Numeric[2]); // Two
Get Value by Key Name
Sometimes, we can also need to get value by passing the Key name of Enums, then we can have this code simply
enum Numeric{
Zero,
One,
Two
}
console.log(Numeric["Two"]); // 2
As you can see in the above code, we have directly passed EnumName["EnumKey"]
which will give us Enum Value.
You may also like to read:
What is JQuery IsNumeric like function in Javascript?
Password and Confirm password validation using Javascript
Encrypt and Decrypt string in Javascript
How to convert iso date to date-format JavaScript?
Convert Image to base64 string using Javascript