How to iterate over the keys and values in an object in CoffeeScript?

Use for x,y of L. Relevant documentation.

ages = {}
ages["jim"] = 12
ages["john"] = 7

for k,v of ages
  console.log k + " is " + v

Outputs

jim is 12
john is 7

You may also want to consider the variant for own k,v of ages as mentioned by Aaron Dufour in the comments. This adds a check to exclude properties inherited from the prototype, which is probably not an issue in this example but may be if you are building on top of other stuff.

Leave a Comment