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

32,067

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 }

Share:
32,067

Related videos on Youtube

Giles Bowkett
Author by

Giles Bowkett

Updated on April 30, 2020

Comments

  • Giles Bowkett
    Giles Bowkett about 4 years

    eg:

    wtf

    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
      Trevor Burnham over 12 years
      To 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
    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
    Andrey Mikhaylov - lolmaus almost 10 years
    Why do you need eval in the last line?
  • bcherny
    bcherny over 9 years
    this is pretty clever, but a bad idea from a security/perf/best practice point of view
  • Danyel
    Danyel about 9 years
    Depending on your coffeescript version, this might not be possible.
  • Andrii Gladkyi
    Andrii Gladkyi over 8 years
    That's the answer. Thanks!
  • bcherny
    bcherny over 7 years
    @KonstantinSchubert Yes, it's a special case of string interpolation. See coffeescript.org/#strings
  • Konstantin Schubert
    Konstantin Schubert over 7 years
    @bcherny Ah, thanks! I wasn't aware that string interpolation requires double quotes.
  • phil294
    phil294 over 3 years
    I dont think you even need the quotes. [ 1 + 2 ]: 3 will also work.