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

后端 未结 6 2015
野趣味
野趣味 2021-01-07 16:00

eg:

\"wtf\"

So:

foo = \"asdf\"
{foo: \"bar\"}
eval foo

# how do I g         


        
相关标签:
6条回答
  • 2021-01-07 16:33

    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'}.

    0 讨论(0)
  • 2021-01-07 16:39

    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'
    
    0 讨论(0)
  • 2021-01-07 16:49

    Try this:

    foo = "asdf"
    
    eval "var x = {#{foo}: 'bar'}"
    alert(x.asdf)
    
    0 讨论(0)
  • 2021-01-07 16:53

    Somewhat ugly but a one-liner nonetheless (sorry for being late):

    { "#{foo}": bar }

    0 讨论(0)
  • 2021-01-07 16:54

    If you're looking to use Coffeescript's minimal syntax for defining your associative array, I suggest creating a simple two line method to convert the variable name keys into the variable values after you've defined the array.

    Here's how I do it (real array is much larger):

    @sampleEvents = 
       session_started:
              K_TYPE: 'session_started'
              K_ACTIVITY_ID: 'activity'
    
       session_ended:
              K_TYPE: 'session_ended'
    
       question_answered:
              K_TYPE: 'question_answered'
              K_QUESTION: '1 + 3 = '
              K_STUDENT_A: '3'
              K_CORRECT_A: '4' #optional
              K_CORRECTNESS: 1 #optional
              K_SECONDS: 10 #optional
              K_DIFFICULTY: 4 #optional
    
    
    for k, event of @sampleEvents
        for key, value of event
            delete event[key]
            event[eval(key.toString())] = value
    

    The SampleEvents array is now:

    { session_started: 
       { t: 'session_started',
         aid: 'activity',
         time: 1347777946.554,
         sid: 1 },
      session_ended: 
       { t: 'session_ended', 
         time: 1347777946.554, 
         sid: 1 },
      question_answered: 
       { t: 'question_answered',
         q: '1 + 3 = ',
         sa: '3',
         ca: '4',
         c: 1,
         sec: 10,
         d: 4,
         time: 1347777946.554,
         sid: 1 },
    
    0 讨论(0)
  • 2021-01-07 16:58

    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

    0 讨论(0)
提交回复
热议问题