2

I have the following enum

export enum Operators {
    Equal = "1",
    NotEqual = "2",
    GreatherOrEqual = "3",
    LessOrEqual = "4",
    Contains = "5",
    Null = "6",
    NotNull = "7",
    Between = "8",
    StartsWith = "9",
    EndsWith = "10"
}

I need to recover the enum key from the value that is stored. I have created the following:

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 ];
}

The function returns what I need, but is there any simpler way to get the key?

1
  • 1
    You could use Object.entries(Operators). It returns an array of [ key, value ] Commented May 22, 2019 at 20:00

3 Answers 3

2

I am using this function for any enum

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] : '';
}

Tests using jest

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

Comments

2

You can use a combination of Object.entries and a Map:

const operators = new Map(
  Object.entries(Operators)
    .map(entry => entry.reverse()) as [Operators, keyof typeof Operators][]
);

console.log(
  operators.get(Operators.Between) // Between
)

Note that this is way easier to do when your enum contains numbers instead of strings.

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"

Comments

1

Perfect. Thank you Paul. I have modified it in the following way:

GetEnumTextByValue ( valueOperator: string ): string {
    let operator: string;
    for ( let [ key, value ] of Object.entries( Operators ) ) {
        value === valueOperator ? operator = key : null;
    }
    return operator;
}

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.