skip to Main Content

I have a enum object and how to get the object value when passing the key using typescript

Below switch case works what if the enum object is so long, any other better way to do

export enum AllGroup = {
'GROUP_AUS': 'A'
'GROUP_IN': 'B'
}

var input = 'GROUP_IN'

Expected Output

B

Tried

  const renderValue = (input: string): JSX.Element => {
    switch (input) {
      case AllGroup.GROUP_AUS:
        return <>A</>;
      case AllGroup.GROUP_IN:
        return <>B</>;

    }
    return <div></div>;
  };

2

Answers


  1. You can directly access the enum by the key:

    enum AllGroup {
      GROUP_AUS = "A",
      GROUP_IN = "B",
    }
    
    const renderValue = (input: string) => {
      return AllGroup[input];
    };
    
    console.log(renderValue("GROUP_IN")); // Output: B
    
    
    Login or Signup to reply.
  2. If you want a more formalized approach, you can create a function that returns an object with methods for getting values by keys or returns all values. In the below case get() and getAll().

    Refer the below code for reference :

    function createEnum(values) {
      return {
        get: key => values[key],
        getAll: () => values
      };
    }
    
    const AllGroup = createEnum({
      GROUP_AUS: 'A',
      GROUP_IN: 'B',
    });
    
       
    
    console.log(AllGroup.get('GROUP_AUS')); // Outputs: A
    console.log(AllGroup.get('GROUP_IN'));  // Outputs: B
    console.log(AllGroup.get('xyz'));       // Outputs: undefined
    console.log(AllGroup.getAll());         // Outputs:{ "GROUP_AUS": "A","GROUP_IN":"B"}
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search