I was trying to extract strings with using an enum such as:
var INGREDIENT = { COFFEE: "coffee"}
and then later wanted to have a cost scale for the ingredients
var COST = { coffee: 1 }
but i wanted to extract coffee to use the string: INGREDIENT.COFFEE like so:
var COST = {INGREDIENT.COFFEE: 1 }; //target
but it was showing an error that .
is incorrect.
I was resorting to:
var COST= {};
COST[INGREDIENT.COFFEE] = 1;
Is there something i am doing, preventing me from doing it like my //target
In ES2015 you can write
var COST = { [INGREDIENT.COFFEE]: 1 };
Older versions of JavaScript (still very much in common use) did not allow that, however, and the only choice was to use a separate assignment via the []
notation, as in the OP:
var COST= {};
COST[INGREDIENT.COFFEE] = 1;
If you don't like having it be two expressions, you can always exploit the magic of functions:
var COST = function() {
var value = {};
value[INGREDIENT.COFFEE] = 1;
return value;
}();
That's pretty ugly of course, but it's good to know in case you really need to squeeze some object-building code into some context where you can only pass an expression.
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