Fallenreaper
Fallenreaper

Reputation: 10704

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

Upvotes: 6

Views: 2410

Answers (1)

Pointy
Pointy

Reputation: 413737

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.

Upvotes: 10

Related Questions