Reputation: 2145
Javascript doesn't have a general object iterator, to allow something like:
foo.iterate (function (key, value) {
console.log ("key->" + key + " value->" + value);
});
Seems convenient and trivial to implement. Is something like this built in to any popular libraries? I don't want to reinvent the wheel, and if do something like this would like to follow naming (and semantic) conventions for any existing method.
So does a general iterator like this exist somewhere?
added: I've been tinkering around and added an iterator function to Object.prototype. This slowed down the for loop by a factor of about 20! I wasn't even calling the new iterator method, just adding it to Object's prototype greatly slowed down for loops. I'm assuming this negates an optimization in Chrome. This would explain why none of these libraries mentioned add an iteration method to Object.
Upvotes: 0
Views: 1729
Reputation: 780655
You can use for-in
, but you need to add extra code to distinguish properties of the object itself from those inherited from a prototype:
Object.prototype.iterate = function(callback) {
for (var key in this) {
if (this.hasOwnProperty(key)) {
callback(key, this[key]);
}
}
}
Every object now has an iterate() method since we've attached this function to the Object prototype. Now, you can use the code example from the OP to iterate over the properties of the object foo
.
Note: there are NO "classes" in Javascript, and functions are first class data types. So, any functions or "methods" added to the object will be iterated over using this function as well.
Upvotes: 2
Reputation: 1885
Yes! Most popular libraries implement some form of this. Here's a few examples:
jQuery.each(). Here's an example:
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
Underscore _.each(). Here's an example of this one:
_.each([1, 2, 3], alert);
Apparently, Javascript 1.7 has an iterator built in
See also the Prototype framework's Enumerable, albeit a bit dated.
I would highly recommend underscore for it's wide variety of utility methods to make manipulating JavaScript objects and arrays easy, even for more sophisticated operations. This has the advantage of working client and server side without having lots of DOM manipulation functionality built-in like jQuery, Dojo, and Prototype.
If you're looking to implement a simple version of each() for arrays, checkout the functional programming chapter in Eloquent Javascript and his implementation:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
forEach(["Wampeter", "Foma", "Granfalloon"], print);
Upvotes: 1
Reputation: 55740
Why not a simple for in
loop ?
for(var key in obj) {
console.log ("key->" + key + " value->" + obj[key]);
}
Upvotes: 1
Reputation: 94101
It doesn't, but here's a way to do it without libraries or extra functions (other than for..in
loop):
Object.keys(foo).forEach(function(key){
console.log(this[key]);
}, foo);
Upvotes: 4