21

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

2
  • 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. Commented Sep 12, 2018 at 13:15
  • What do you want the keys to be? The value of the enum? Commented Sep 12, 2018 at 13:16

1 Answer 1

50

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]);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.