简体   繁体   English

Typescript - 按字符串索引查找枚举

[英]Typescript - Find enum by string Index

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 ?这看起来真的很简单,我只是遗漏了一些东西,但是我如何根据字符串 Index 返回正确的 Enum ?

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"当我只有字符串“2”时,我只想返回 Locale.Kenya

I've had a look at Object.values and Object.keys but didn't understand how to get the Enum back.我看过 Object.values 和 Object.keys 但不明白如何让 Enum 回来。

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); function getEnumKeyByEnumValue(myEnum, enumValue) { let keys = Object.keys(myEnum).filter(x => myEnum[x] == enumValue); return keys.length > 0 ?返回keys.length > 0 ? keys[0] : null;键[0]:空; } }

You can use Object.entries(Locales) for obtain a two dimensional array which in the deep layer have [Country, string].您可以使用 Object.entries(Locales) 获得一个二维数组,在深层有 [Country, string]。 This is an example:这是一个例子:

[ ['English', 'en'], ['China', '0']['Nigeria', '1'], ['Kenya', '2'] ] [ ['英语', 'en'], ['中国', '0']['尼日利亚', '1'], ['肯尼亚', '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这将返回肯尼亚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM