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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With