Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Enum as Object keys [duplicate]

Tags:

javascript

I have an Enum:

   const ingredients = {
      BREAD_BOTTOM: 'BreadBottom',
      BREAD_TOP: 'BreadTop',
      MEAT: 'Meat',
      BACON: 'Bacon',
      CHEESE: 'Cheese',
      SALAD: 'Salad'
   };

Now I want to create a list of ingredients using this Enum, something like:

    listOfIngredients: {
      ingredients.BREAD_TOP: 1,
      ingredients.BACON: 1,
      ingredients.CHEESE: 2,
      ingredients.MEAT: 2,
      ingredients.BREAD_BOTTOM: 1,
    }

I try some variations such as ${ingredients.BREAD_TOP} but I cannot make the list of ingredients have as key the Enum values

like image 900
Icaro Avatar asked Sep 12 '18 13:09

Icaro


1 Answers

You can wrap the keys in [] to evaluate their value before using them as keys

const listOfIngredients: {
      [ingredients.BREAD_TOP]: 1,
      [ingredients.BACON]: 1,
      [ingredients.CHEESE]: 2,
      [ingredients.MEAT]: 2,
      [ingredients.BREAD_BOTTOM]: 1,
}

To access a value, just do:

console.log(listOfIngredients[ingredients.BREAD_TOP]);

Here's a snippet:

let ingredients = {
  BREAD_BOTTOM: 'BreadBottom',
  BREAD_TOP: 'BreadTop',
  MEAT: 'Meat',
  BACON: 'Bacon',
  CHEESE: 'Cheese',
  SALAD: 'Salad'
};

const listOfIngredients= {
      [ingredients.BREAD_TOP]: 1,
      [ingredients.BACON]: 1,
      [ingredients.CHEESE]: 2,
      [ingredients.MEAT]: 2,
      [ingredients.BREAD_BOTTOM]: 1
};

console.log(listOfIngredients[ingredients.BREAD_TOP]);
like image 127
Ayush Gupta Avatar answered Oct 01 '22 19:10

Ayush Gupta