Writing a JSON Key with an Enumeration

I tried to extract strings using an enumeration, for example:

var INGREDIENT = { COFFEE: "coffee"}

and then later wanted to have a cost scale for ingredients

var COST = { coffee: 1 }

but I wanted to extract coffee to use the line: INGREDIENT.COFFEE like this:

var COST = {INGREDIENT.COFFEE: 1 };  //target

but he showed an error that .is incorrect.

I resorted to:

var COST= {};
COST[INGREDIENT.COFFEE] = 1;

Is there something that I do, not letting me do it like mine //target

+4
source share
1 answer

In ES2015 you can write

var COST = { [INGREDIENT.COFFEE]: 1 };

Older versions of JavaScript (still very commonly used) did not allow this, however, and the only choice was to use a separate assignment using a notation [], as in OP:

var COST= {};
COST[INGREDIENT.COFFEE] = 1;

, , :

var COST = function() {
  var value = {};
  value[INGREDIENT.COFFEE] = 1;
  return value;
}();

, , - - - , .

+6

Source: https://habr.com/ru/post/1620214/


All Articles