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
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With