in CoffeeScript, how can I use a variable as a key in a hash?
Solution 1
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
Solution 2
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'}
.
Solution 3
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'
Solution 4
Somewhat ugly but a one-liner nonetheless (sorry for being late):
{ "#{foo}": bar }
Related videos on Youtube
Giles Bowkett
Updated on April 30, 2020Comments
-
Giles Bowkett about 4 years
eg:
So:
foo = "asdf" {foo: "bar"} eval foo # how do I get {"asdf": "bar"} ? # this will throw parse error: {(eval foo): "bar"}
This is a simple syntax question: how do I get CoffeeScript to construct a hash dynamically, rather than doing it by hand?
-
Trevor Burnham over 12 yearsTo be clear,
{(eval(foo)): "bar"}
is invalid JavaScript; the object literal syntax only allows literal strings as keys. To support dynamic keys, CoffeeScript would have to convert that code to something like__obj = {}; __obj[eval(foo)] = "bar";
.
-
-
Brian Genisio over 12 years+1. I have actually found myself extending my prototypes to include a generic function like
getByKey
that does this for me when I need to do it often. -
Andrey Mikhaylov - lolmaus almost 10 yearsWhy do you need
eval
in the last line? -
bcherny over 9 yearsthis is pretty clever, but a bad idea from a security/perf/best practice point of view
-
Danyel about 9 yearsDepending on your coffeescript version, this might not be possible.
-
Andrii Gladkyi over 8 yearsThat's the answer. Thanks!
-
bcherny over 7 years@KonstantinSchubert Yes, it's a special case of string interpolation. See coffeescript.org/#strings
-
Konstantin Schubert over 7 years@bcherny Ah, thanks! I wasn't aware that string interpolation requires double quotes.
-
phil294 over 3 yearsI dont think you even need the quotes.
[ 1 + 2 ]: 3
will also work.