Home > Mobile >  How to get enum key with enum value in typescript
How to get enum key with enum value in typescript

Time:08-04

In the project i am working on we have this widely used enum:

export enum A{
    Document = '1',
    Person = '2',
    Organization = '3',
    Equipment = '4',
    Location = '5',
    Event = '6',
    Link = '7',
    Target = '8',
}

Example: I want to get Organization with A['3']

CodePudding user response:

You can use Object.entries to do that:

enum A{
    Document = '1',
    Person = '2',
    Organization = '3',
    Equipment = '4',
    Location = '5',
    Event = '6',
    Link = '7',
    Target = '8',
}

const param = '3';
const value = Object.entries(A).find(([_, v]) => v === param)![0];

TS Playground

CodePudding user response:

Object keys

enum A {
    Document = '1',
    Person = '2',
    Organization = '3',
    Equipment = '4',
    Location = '5',
    Event = '6',
    Link = '7',
    Target = '8',
}

console.log(Object.keys(A)[Object.values(A).indexOf("1")]);

  • Related