最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Writing the Key of JSON with an enum - Stack Overflow

programmeradmin2浏览0评论

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

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

Share Improve this question asked Dec 15, 2015 at 23:02 FallenreaperFallenreaper 10.7k15 gold badges75 silver badges140 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

In ES2015 you can write

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

Older versions of JavaScript (still very much in mon 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.

发布评论

评论列表(0)

  1. 暂无评论