Last active
March 10, 2021 06:03
-
-
Save getify/9104721 to your computer and use it in GitHub Desktop.
default object-iterator for ES6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; | |
} | |
}; | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]]; | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.