allesklar
allesklar

Reputation: 9600

Using a variable as a hash key in Coffeescript

Let's say I have this hash in Coffeescript:

exercises =
  stretchedPrayer:
    name: "Stretched Prayer"
    sound: "28-stretched-prayer"
  bandStretch:
    name: "Band Stretch"
    sound: "13-band-stretch"

I can correctly get the name of the first exercise with the following code:

exercises.stretchedPrayer.name

What I want to do is call the same name but I will know which exercise I want from a variable extracted from an id on the web page.

In other words, if I have a variable such as

myExercise = "stretchedPrayer"

How can I get the name of the practice in the hash just using this variable?

Upvotes: 0

Views: 2250

Answers (1)

Dogbert
Dogbert

Reputation: 222288

Just use square brackets, like you would do in JavaScript.

exercises[myExercise].name

object[property] is the same as object.<<property's value>>

Upvotes: 4

Related Questions