Choose the Enum in a dynamic manner

I have three enums

Country_INDIA, Country_USA,Country_AUSTRALIA
. During runtime, the specific country name is determined (it could be either INDIA, USA, or AUSTRALIA). Is it possible to select the correct enum based on the country name at runtime? For instance, if the country name is USA, I need to choose the 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); // Retrieve the interest rate from the 'Country_USA' enum

Answer №1

Enum may not be the most efficient solution for your situation; perhaps utilizing a map would provide a simpler approach:

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

Answer №2

To enable access to enums in JavaScript, it is necessary to expose them.

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

// Accessing the enums dynamically is now possible
let countryName = "Country_USA";
let countryEnum = countries[countryName];

if (countryEnum) {
  console.log(countryEnum.INTEREST_RATE); // Outputs: 3%
} else {
  console.log("Country not found");
}

Alternatively, using a plain old JavaScript object (POJO) instead of an enum may be a simpler solution.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamically Adding Filenames in Vue.js with v-for Iteration

I'm currently facing an issue with dynamically adding inputs to my Vue 3 application. Specifically, I have a component that adds both text and file inputs dynamically. While the text input works flawlessly using v-model, the file input requires me to ...

Guide to retrieve the file name into a text box upon selection (Avoid displaying as c:/fake path/)

I am trying to achieve the functionality where after choosing a file in a file input, the file name is automatically displayed in a text box named file_name without needing to click or submit any button. Unfortunately, I have been unable to find the correc ...

What is the best way to save data from an ng-repeat array in MEANJS?

I've been exploring MEANJS at meanjs.org and I'm having trouble storing array data for ng-repeat in the deal object, which includes dealtype and dealprice. Despite setting up addFields for the ng-repeat input tag in the create form, the data isn& ...

Can the Angular.js scope be maintained while also making changes to the template?

I am currently facing a challenge with my directive. In the snippet below, I am attempting to extract content from a template, append it to the layout, and then compile it: var $template = angular.element("<div></div>"); $template.append($co ...

Struggling to implement the .map method with TypeScript?

I'm currently grappling with incorporating TypeScript into my .map method and encountering the error message below. Additionally, I'm uncertain about the meaning of the 'never' keyword. TS2339: Property 'fname' does not exist ...

Updating div content dynamically with Jquery and PHP variable

How can I continuously update a div with the current date and time using PHP variable and Jquery? Here is my PHP file containing the variable date: <?php $date = date('d/m/Y H:i:s'); ?> And here's the code in my HTML file: <!DOCT ...

What is the procedure for adding a URL path in jQuery?

When using $(this).attr("href"); in the jQuery Ajax url field, it correctly retrieves the URL path. However, if I try to use a prefix in front of it like this: $.ajax({ type: 'GET' url: 'api/' + $(this).attr("href"); }) the co ...

Exploring Angular5 Navigation through Routing

I have been working with Angular routing and I believe that I may not be using it correctly. While it is functional, it seems to be causing issues with the HTML navbars - specifically the Info and Skills tabs. When clicking on Skills, a component popup s ...

What is the process for clearing the input value of a View from another View?

My situation seems simple and straightforward, yet I am struggling to achieve the desired output. In this scenario, I have two HTML pages named Index.htm and Main.htm, as well as a script page named mscript.js. Index.htm contains a button (Clear), and Mai ...

Requesting data with Ajax: utilizing parameters in the format of x-www-form-urlencoded

When adding parameters to a get/post request, it is important to encode them in application/x-www-form-urlencoded form. Is it necessary to encode values each time? Does JavaScript provide a method for encoding values? What options are available for caching ...

When I use my loop to generate Google Map markers, the positioning is not accurate and the markers do not appear on the map. However, manually inputting the positions

There seems to be an issue with displaying Google map markers based on objects in the markers array after looping through it. I noticed that when creating a second component and setting the position manually, the marker appears correctly. However, upon ins ...

Toggle the class and execute the order within a jQuery script

When the mouse moves in, the jQuery trigger enters the status. $(".test").bind("mouseenter mouseout", function(event) { $(this).toggleClass("entered"); alert("mouse position (" + event.pageX + "," + event.pageY + ")"); }); .entered { ...

What is the best way to manage sessions in angularjs using javascript?

Only at two specific instances in the application should the login prompt be displayed: When trying to access a page that requires login while not logged in, such as my profile page. When attempting an action that necessitates ...

Save and showcase SQL, PHP, HTML, and JS code exactly as it is preserved in MYSQL database

Is there a way to store and display complete JS, PHP, and HTML code in MySQL without altering the format? The stored PHP code should appear as: <?php echo "something"; ?> And not just: something For JavaScript: <script> document.write(&ap ...

Invoke the dispatch function from React-Redux in a stateless component with the help of a wrapper

I have a React-Redux store that is wrapped in a next-redux-wrapper. I am facing an issue where I cannot dispatch a function outside of a react component due to the wrapper. Is there a way to import the store and use dispatch while still using the wrapper? ...

Using jQuery and AJAX manipulates the value of my variable

My AJAX request seems to be causing jQuery to change the variable that is passed to it. Here is the JavaScript code: <script type="text/javascript"> function ResolveName(id) { $.ajax({ url : 'resolvename.php', ...

Tips for getting information from a GET/POST response message with superagent

I'm currently utilizing Node.js and Superagent for testing my server implementation. I have successfully sent a Superagent GET request and received a positive response with the code provided below. My goal is to extract and log only the "id" value fro ...

Nuxt 2.5 and higher do not recognize the definition of Global

After utilizing Nuxt 2.1 in my app, I proceeded to upgrade it gradually and everything was fine until Nuxt 2.4. However, starting from version 2.5 and above, production builds are breaking with an error stating global is not defined. The location of the e ...

Issue with two Jquery slider forms

Within a Jquery slider, I have implemented two distinct forms (using this specific Jquery slider: http://tympanus.net/Tutorials/FancySlidingForm/) . My goal now is to establish JavaScript/jQuery validation for these two forms separately BASED on the form ...

Informing the parent window of the child window's activities in order to adjust the timer for the user timeout feature

Within my Jquery function, I have implemented a feature that darkens the screen after a period of user inactivity. This triggers a pop-up window giving the user the option to stay logged in by clicking a button. If there is no response within the set time ...