Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing the Key of JSON with an enum

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

like image 446
Fallenreaper Avatar asked Dec 15 '15 23:12

Fallenreaper


1 Answers

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.

like image 69
Pointy Avatar answered Nov 14 '22 23:11

Pointy