jhchen
jhchen

Reputation: 14767

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.

Upvotes: 4

Views: 2403

Answers (5)

bcherny
bcherny

Reputation: 3172

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

The syntax looks like this:

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

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

Upvotes: 3

colllin
colllin

Reputation: 9789

If you're using underscore, you can use the _.object function, which is the inverse of the _.pairs function.

_.pairs({a: 1, b: 'hello'})
//=> [['a', 1], ['b', 'hello']]

_.object([['a', 1], ['b', 'hello']])
//=> {a: 1, b: 'hello'}

So, assuming myKey = 'superkey' and myValue = 100 you could use:

var obj = _.object([[myKey, myValue]]);
//=> obj = {superkey: 100}

Upvotes: 1

colllin
colllin

Reputation: 9789

(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.

Upvotes: 4

Renato Zannon
Renato Zannon

Reputation: 29971

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.

Upvotes: 4

Brandon Buck
Brandon Buck

Reputation: 7181

Depending on how complex your key is you can always use a variable name matching your key and use it to define an object, like this:

myKey = "Some Value"
obj = {myKey}

Which will compile to:

var myKey, obj;

myKey = "Some Value";

obj = {
  myKey: myKey
};

So what you end up with is something close to what you seek, but that requires your keys to be valid variable names.

Upvotes: 1

Related Questions