skip to Main Content

I have three enums Country_INDIA, Country_USA,Country_AUSTRALIA. At runtime, the country name is decided (could be one of INDIA or USA or AUSTRALIA). Is there a way I can pick the right enum based on the country name at runtime. For example, if the country name is USA , I want to pick Country_USA enum.

enum Country_INDIA {

  INTREST_RATE = '10%',
  MIN_INVESTMENT_DURATION = "5YRS"

};

enum Country_USA {

  INTREST_RATE = '3%',
  MIN_INVESTMENT_DURATION = "3YRS"
};

enum Country_AUSTRALIA {

  INTREST_RATE = '5%',
  MIN_INVESTMENT_DURATION = "2YRS"
};

let country_enum = "Country_"+"USA" 

console.log(country_enum.INTREST_RATE); // get the interst rate from 'Country_USA' enum

2

Answers


  1. You need to make the enums available to JavaScript

    enum CountryINDIA {
      INTEREST_RATE = '10%',
        MIN_INVESTMENT_DURATION = "5YRS"
    }
    
    enum CountryUSA {
      INTEREST_RATE = '3%',
        MIN_INVESTMENT_DURATION = "3YRS"
    }
    
    enum CountryAUSTRALIA {
      INTEREST_RATE = '5%',
        MIN_INVESTMENT_DURATION = "2YRS"
    }
    
    // Create a mapping object
    const countries = {
      Country_INDIA: CountryINDIA,
      Country_USA: CountryUSA,
      Country_AUSTRALIA: CountryAUSTRALIA,
    };
    
    // Now you can dynamically access the enums
    let countryName = "Country_USA";
    let countryEnum = countries[countryName];
    
    if (countryEnum) {
      console.log(countryEnum.INTEREST_RATE); // Outputs: 3%
    } else {
      console.log("Country not found");
    }
    

    Alternatively don’t use an enum, a POJO will be simpler.

    Login or Signup to reply.
  2. I think using enums is not the optimal way to solve your case:
    a map would be easier

    const countryData = {
      USA: {
        INTEREST_RATE = 10,
        MIN_INVESTMENT_DURATION = "5YRS"
      },
      UK: {
        INTEREST_RATE = 1,
        MIN_INVESTMENT_DURATION = "10YRS"
      }
    
    };
    
    const interestRate = countryData['USA'].INTEREST_RATE; // 10
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search