Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an object (an "associate array" so to say - also known as a plain JavaScript object):

obj = {} obj["Foo"] = "Bar" obj["bar"] = "Foo" 

I want to iterate over obj using CoffeeScript as follows:

# CS for elem in obj 

bu the CS code above compiles to JS:

// JS for (i = 0, len = obj.length; i < len; i++) 

which isn't appropriate in this case.


The JavaScript way would be for(var key in obj) but now I'm wondering: how can I do this in CoffeeScript?

like image 467
jhchen Avatar asked Jun 20 '11 08:06

jhchen


People also ask

How do you iterate through the keys of an object?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.

Which loop is used to iterate over all the keys in an object?

The for...in loop will traverse all integer keys before traversing other keys, and in strictly increasing order, making the behavior of for...in close to normal array iteration.

How do I iterate an object in node JS?

Since Javascript 1.7 there is an Iterator object, which allows this: var a={a:1,b:2,c:3}; var it=Iterator(a); function iterate(){ try { console. log(it. next()); setTimeout(iterate,1000); }catch (err if err instanceof StopIteration) { console.


1 Answers

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.

like image 52
Nick Avatar answered Oct 11 '22 10:10

Nick