Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript one liner for creating hashmap with variable key

Is it possible to do the following in one line in coffeescript?

obj = {}
obj[key] = value

I tried:

obj = { "#{key}": value }

but it does not work.

like image 686
jhchen Avatar asked Dec 11 '22 09:12

jhchen


2 Answers

It was removed from the language

Sorry for being tardy -- if I remember correctly, it was because some of our other language features depend on having the key known at compile time. For example, method overrides and super calls in executable class bodies. We want to know the name of the key so that a proper super call can be constructed.

Also, it makes it so that you have to closure-wrap objects when used as expressions (the common case) whenever you have a dynamic key.

Finally, there's already a good syntax for dynamic keys in JavaScript which is explicit about what you're doing: obj[key] = value.

There's something nice about having the {key: value, key: value} form be restricted to "pure" identifiers as keys.

like image 131
Renato Zannon Avatar answered Feb 21 '23 09:02

Renato Zannon


(obj = {})[key] = value

will compile to

var obj;

(obj = {})[key] = value;

This is normal javascript. The only benefit you get from coffeescript is that you don't have to pre-declare var s because it does it for you.

like image 22
colllin Avatar answered Feb 21 '23 08:02

colllin