Euphe
Euphe

Reputation: 3709

Why doesn't this coffescript code work?

I am trying to make a function that lists all properties of an object

showProps = (obj) ->
 result = ""
 result+= String(i+ ' = ' + obj[i] + '\n') for i in obj when obj.hasOwnProperty(i)
 return result
O = {A:1}
alert showProps O

Why does the function return nothing?

Upvotes: 0

Views: 68

Answers (3)

Aaron Dufour
Aaron Dufour

Reputation: 17535

CoffeeScript's for...in loops are for looping over arrays. To iterate over an object, you want for...of (which compiles to Javascript's for...in).

If you use

result+= String(i+ ' = ' + obj[i] + '\n') for i of obj when obj.hasOwnProperty(i)

then you will get the result you're looking for.

As @muistooshort pointed out, you can get the hasOwnProperty part for free in CoffeeScript with own, which makes the code a bit simpler:

result+= String(i+ ' = ' + obj[i] + '\n') for own i of obj

Upvotes: 1

topr
topr

Reputation: 4622

It doesn't work because you used wrong operator. in is meant to be used for iterating through collections, like an array for example. You would like to use of operator.

Besides I changed your example a bit to make it more CoffeeScript way:

showProps = (obj) ->
  result = ""
  result += "#{i} = #{v} \n" for i, v of obj when obj.hasOwnProperty(i)
  result
anObject = A:1
alert showProps anObject

Upvotes: 0

Bergi
Bergi

Reputation: 665517

You want an for [own] of-loop to iterate over properties:

showProps = (obj) ->
 result = ""
 result+= String(i+ ' = ' + v + '\n') for own i, v of obj
 return result
O = {A:1}
alert showProps O

Btw, you don't need the explicit String call since you're concatenating strings anyway, and your whole function could be defined more easily as an array comprehension:

showProps = (obj) ->
  (i+' = '+v  for own i, v of obj).join('\n')

Upvotes: 1

Related Questions