Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 935
Giles Bowkett Avatar asked Oct 08 '11 20:10

Giles Bowkett


People also ask

How do you use variable name as object key?

Use bracket notation to get an object's value by a variable key, e.g. obj[myVar] . The variable or expression in the brackets gets evaluated, so if a key with the computed name exists, you will get the corresponding value back. Copied!

How can you get the value in an object's key using a variable referencing key?

To get value in an object's key using a variable referencing that key with JavaScript, we can use square brackets. console. log(obj[name]); to get the name property of the obj object with obj[name] .

How do I declare a variable in CoffeeScript?

In JavaScript, before using a variable, we need to declare and initialize it (assign value). Unlike JavaScript, while creating a variable in CoffeeScript, there is no need to declare it using the var keyword. We simply create a variable just by assigning a value to a literal as shown below.


1 Answers

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

like image 112
bcherny Avatar answered Sep 19 '22 15:09

bcherny