2

This seems like something really simple and i'm just missing something but how do i return the correct Enum based on the string Index ?

Enum

export enum Locales {
    English = "en",
    China = "0",
    Nigeria = "1",
    Kenya = "2"
}

I just want to return Locale.Kenya when all i have is the string "2"

I've had a look at Object.values and Object.keys but didn't understand how to get the Enum back.

Rhodes73
  • 167
  • 2
  • 9
  • Check this question: https://stackoverflow.com/questions/57966858/how-to-reverse-typing-on-a-typescript-enum/57970647#57970647 Reverse mappings are only possible for numeric non const enums. – Artem Bozhko Oct 28 '20 at 08:49

2 Answers2

4

As described in the handbook:

Keep in mind that string enum members do not get a reverse mapping generated at all.

That means there is no simple reverse mapping in your case.

You can try some custom functions, like this:

function getEnumKeyByEnumValue(myEnum, enumValue) { let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue); return keys.length > 0 ? keys[0] : null; }
1

You can use Object.entries(Locales) for obtain a two dimensional array which in the deep layer have [Country, string]. This is an example:

[ ['English', 'en'], ['China', '0']['Nigeria', '1'], ['Kenya', '2'] ]

If you want to obtain Kenya you can filter this array for search this value like this:

Object.entries(Locales).find(local=>local[1]==='2')[0]

This returns Kenya

David
  • 156
  • 4