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.

1

2 Answers 2

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; }
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.