0

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

1 Answer 1

3

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/

Sign up to request clarification or add additional context in comments.

1 Comment

Predictable and consistent results are quite good when it comes to programing languages. a = { 'test': '0', 'super': '1' } looks good to me as it avoids ambiguity. Otherwise coffeescript is having to make an opinionated guess and in this case it guesses wrong. Thanks for your detailed answer and workaround function! Usefull!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.