in CoffeeScript, how can I use a variable as a key in a hash?

微笑、不失礼 提交于 2019-12-01 02:03:35

For anyone that finds this question in the future, as of CoffeeScript 1.9.1 interpolated object literal keys are supported!

The syntax looks like this:

myObject =   a: 1   "#{ 1 + 2 }": 3 

See https://github.com/jashkenas/coffeescript/commit/76c076db555c9ac7c325c3b285cd74644a9bf0d2

Why are you using eval at all? You can do it exactly the same way you'd do it in JavaScript:

foo    = 'asdf' h      = { } h[foo] = 'bar' 

That translates to this JavaScript:

var foo, h; foo = 'asdf'; h = {}; h[foo] = 'bar'; 

And the result is that h looks like {'asdf': 'bar'}.

CoffeeScript, like JavaScript, does not let you use expressions/variables as keys in object literals. This was support briefly, but was removed in version 0.9.6. You need to set the property after creating the object.

foo = 'asdf'  x = {} x[foo] = 'bar' alert x.asdf # Displays 'bar' 

Somewhat ugly but a one-liner nonetheless (sorry for being late):

{ "#{foo}": bar }

If you're looking to use Coffeescript's minimal syntax for defining your associative array, I suggest creating a simple two line method to convert the variable name keys into the variable values after you've defined the array.

Here's how I do it (real array is much larger):

@sampleEvents =     session_started:           K_TYPE: 'session_started'           K_ACTIVITY_ID: 'activity'     session_ended:           K_TYPE: 'session_ended'     question_answered:           K_TYPE: 'question_answered'           K_QUESTION: '1 + 3 = '           K_STUDENT_A: '3'           K_CORRECT_A: '4' #optional           K_CORRECTNESS: 1 #optional           K_SECONDS: 10 #optional           K_DIFFICULTY: 4 #optional   for k, event of @sampleEvents     for key, value of event         delete event[key]         event[eval(key.toString())] = value 

The SampleEvents array is now:

{ session_started:     { t: 'session_started',      aid: 'activity',      time: 1347777946.554,      sid: 1 },   session_ended:     { t: 'session_ended',       time: 1347777946.554,       sid: 1 },   question_answered:     { t: 'question_answered',      q: '1 + 3 = ',      sa: '3',      ca: '4',      c: 1,      sec: 10,      d: 4,      time: 1347777946.554,      sid: 1 }, 

Try this:

foo = "asdf"  eval "var x = {#{foo}: 'bar'}" alert(x.asdf) 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!