Skip to content

Instantly share code, notes, and snippets.

@getify
Last active March 10, 2021 06:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save getify/9104721 to your computer and use it in GitHub Desktop.
Save getify/9104721 to your computer and use it in GitHub Desktop.
default object-iterator for ES6
if (!(Symbol.iterator in Object.prototype)) {
Object.defineProperty(Object.prototype,Symbol.iterator,{
enumerable: false,
writable: false,
configurable: true,
value: function() {
var o = this;
var idx = -1;
var ks = Object.keys(o);
return {
next: function() {
var v = o[ks[++idx]];
return { done:(idx === ks.length), value: v };
}
};
}
});
}
if (!(Symbol.iterator in Object.prototype)) {
Object.defineProperty(Object.prototype,Symbol.iterator,{
enumerable: false,
writable: false,
configurable: true,
// thanks to: https://twitter.com/juandopazo/status/436298238464122880
value: function*() {
var o = this;
var ks = Object.keys(o);
for (var idx = 0, length = ks.length; idx < length; idx++) {
yield o[ks[idx]];
}
}
});
}
@getify
Copy link
Author

getify commented Mar 31, 2014

Turns out this was decided to NOT be in by default, but of course one could do the above, or a variation which attaches directly to an object that you want to iterate over.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment