mjey
mjey

Reputation: 183

Inline iteration key, value of object in array

In coffeescript we can do this way:

rows = [
    {a: 1}
    {b: 2}
]

for row in rows
    for k,v of row
        alert "#{k}: #{v}"

So why we can't do that this way?:

for k,v of row for row in rows
    alert "#{k}: #{v}"

Upvotes: 0

Views: 660

Answers (3)

Ricardo Tomasi
Ricardo Tomasi

Reputation: 35253

When you try to run for k,v of row for row in rows you get Parse error on line 1: Unexpected 'FOR'.

That's because the moment you put something before for row in rows, it must be an expression, and for k,v of row isn't one. You can verify this by making the prefixed loop an actual expression:

row for k,v of row for row in rows

This compiles. So, the same way you used the postfix form for iterating over rows, you have to postfix the inner one:

alert "#{k}: #{v}" for k,v of row for row in rows

To achieve the separation you want, you need to use then to replace newlines, instead of using a postfix expression:

for row in rows then for k,v of row
    alert "#{k}: #{v}"

Upvotes: 0

epidemian
epidemian

Reputation: 19229

You cannot do it that way, but you can invert the inner loop and put the loop construct after the expression:

for row in rows
  alert "#{k}: #{v}" for k,v of row

And, as that inner loop is also an expression, you can also invert the outer loop the same way :D

alert "#{k}: #{v}" for k,v of row for row in rows

The most similar to what you were trying to write is probably this:

for row in rows then for k,v of row 
  alert "#{k}: #{v}"

Which can be further inlined using another then (the then keyword is usually equivalent to a newline and adding one level of indentation):

for row in rows then for k,v of row then alert "#{k}: #{v}"

All of these alternatives generate the same JS code, so picking one or another will not result on degraded performance or anything like that :D

Upvotes: 4

Ned Batchelder
Ned Batchelder

Reputation: 375744

Because that compound syntax isn't part of the Coffeescript language. Programming languages are not as fluid as human languages.

Upvotes: 0

Related Questions