zzart
zzart

Reputation: 11483

Coffeescript doing list comprehension object

Why coffeescript doesn't return object keys but instead treats value of x as string 'x' ?

coffee> a  = { test: '0', super: '1' }
coffee> x for x,y of a
[ 'test', 'super' ]
coffee> {x:y} for x,y of a
[ { x: '0' }, { x: '1' } ]

Upvotes: 0

Views: 243

Answers (1)

mu is too short
mu is too short

Reputation: 434755

Because that's how CoffeeScript object literal syntax works. Suppose that it worked as you want it to work. What would happen if somewhere I said this:

window.test = 'pancakes'

That would but a test variable into everyone's scope and all of a sudden your a would be:

a = { 'pancakes': '0', super: '1' }

and you'd be left wondering what sort of nonsense your computer is up to. So if the property names were evaluated as variables rather than quote-less strings, we'd all end up writing ugly things like:

a = { 'test': '0', 'super': '1' }

just to get predictable and consistent results.

I think the easiest way to get what you want would be to add a little function:

objectify = (k, v) ->
    o = { }
    o[k] = v
    o

Then you could:

a = (objectify(x, y) for x, y of o)

Demo: http://jsfiddle.net/ambiguous/M8AFk/

Upvotes: 3

Related Questions