Coffeescript one liner for creating a hashmap with a variable key

Is it possible to do the following on a single line in coffeescript?

obj = {}
obj[key] = value

I tried:

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

but that will not work.

+4
source share
5 answers

For those who find this question in the future, the interpolated text keys of the CoffeeScript 1.9.1 instance are still supported!

The syntax is as follows:

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

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

+3
source
(obj = {})[key] = value

will compile in

var obj;

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

javascript. , coffeescript, , var s, .

+4

- , - , , . , . , .

, , ( ), .

, JavaScript , : obj[key] = value.

- {key: value, key: value} "" .

+4

, , , , , :

myKey = "Some Value"
obj = {myKey}

:

var myKey, obj;

myKey = "Some Value";

obj = {
  myKey: myKey
};

, , , , , .

+1

underscore, _.object, _.pairs.

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

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

, myKey = 'superkey' myValue = 100, :

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

All Articles