JavaScript itself doesn't have enums and it doesn't have an obvious way of reading an object's property name by accessing it by the value. However, if you're willing to make your code looks a bit funny, you could try to do what TypeScript does when it compiles enums into JavaScript object.
// TypeScript code…
enum Fruits {
Apple, Banana
}
// … compiles to this JavaScript.
var Fruits;
(function (Fruits) {
Fruits[Fruits["Apple"] = 0] = "Apple";
Fruits[Fruits["Banana"] = 1] = "Banana";
})(Fruits || (Fruits = {}));
It basically simultaneously assigns a key to its value and then makes the value into a key that will hold the the original key. That way you can access this map and get the name you want.
const myFruit = 1
Fruit[myFruit] // => "Banana"
Implementation wise you could go with something like that to avoid the "nastiness" of the machine generated code.
function createEnum(enumeration) {
const result = Object
.entries(enumeration)
.reduce((result, [key, value]) => {
result[result[key] = value] = key
return result
}, {})
return Object.freeze(result)
}
const fruits = createEnum({Apple: 0, Banana: 1})
fruits[1] // => "Banana"
plan? Tryalert(fruit.Apple).