18

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

Icaro
  • 14,585
  • 6
  • 60
  • 75
  • Well, it's not *really* an "enum"; it's an object with string-valued properties. You can use `[ ]` however to extract the property values in the second object literal. – Pointy Sep 12 '18 at 13:15
  • What do you want the keys to be? The value of the enum? – Luca Kiebel Sep 12 '18 at 13:16

1 Answers1

42

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]);
Ayush Gupta
  • 8,716
  • 8
  • 59
  • 92