我有以下枚举
export enum Operators {
Equal = "1",
NotEqual = "2",
GreatherOrEqual = "3",
LessOrEqual = "4",
Contains = "5",
Null = "6",
NotNull = "7",
Between = "8",
StartsWith = "9",
EndsWith = "10"
}
我需要从存储的值中恢复枚举键。我创建了以下内容:
GetEnumTextByValue ( valueOperator: string ): string {
const values: string[] = Object.values( Operators ).filter( v => v == v );
const keys: string[] = Object.keys( Operators ).filter( k => k == k );
const index: number = values.indexOf( valueOperator );
return keys[ index ];
}
该函数返回我需要的东西,但是有没有更简单的方法来获取密钥?
答案 0 :(得分:1)
我将这个函数用于任何枚举
export function getEnumKeyByEnumValue(myEnum: any, enumValue: number | string): string {
let keys = Object.keys(myEnum).filter((x) => myEnum[x] == enumValue);
return keys.length > 0 ? keys[0] : '';
}
使用玩笑进行测试
describe('enum', () => {
enum TestEnumWithNumber {
ZERO
}
enum TestEnumWithString {
ZERO = 'ZERO'
}
it('should return correct key when enum has number values', function () {
const key = getEnumKeyByEnumValue(TestEnumWithNumber, TestEnumWithNumber.ZERO);
expect(key).toBe('ZERO');
});
it('should return correct key when enum has string values', function () {
const key = getEnumKeyByEnumValue(TestEnumWithString, TestEnumWithString.ZERO);
expect(key).toBe('ZERO');
});
});
答案 1 :(得分:1)
您可以结合使用Object.entries
和Map
:
const operators = new Map(
Object.entries(Operators)
.map(entry => entry.reverse()) as [Operators, keyof typeof Operators][]
);
console.log(
operators.get(Operators.Between) // Between
)
请注意,当枚举包含数字而不是字符串时,这样做更容易。
export enum Operators {
Equal = 1,
NotEqual = 2,
GreatherOrEqual = 3,
LessOrEqual = 4,
Contains = 5,
Null = 6,
NotNull = 7,
Between = 8,
StartsWith = 9,
EndsWith = 10
}
Operators[Operators.Between]; // "Between"
答案 2 :(得分:0)
完美。谢谢保罗。 我已经通过以下方式对其进行了修改:
GetEnumTextByValue ( valueOperator: string ): string {
let operator: string;
for ( let [ key, value ] of Object.entries( Operators ) ) {
value === valueOperator ? operator = key : null;
}
return operator;
}