Skip to content

Instantly share code, notes, and snippets.

@PavelKoroteev
Last active July 16, 2020 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PavelKoroteev/61def169dbf23a306fbd53525279e644 to your computer and use it in GitHub Desktop.
Save PavelKoroteev/61def169dbf23a306fbd53525279e644 to your computer and use it in GitHub Desktop.
Simplest object iterator (make object spreadable in console :) )
1. Any object
var obj = {
some: 'thing',
any: 'key',
'1': 'first'
}
obj[Symbol.iterator] = function* objectIterator() {
for (k in this) {
yield this[k];
}
}
console.log([...obj]); // ["first", "thing", "key"]
2. Nummeric
var obj = {
'0': 'zero',
'1': 'first',
'2': 'second',
'3': 'third',
length: 4
};
obj[Symbol.iterator] = function* objectIterator() {
for (let index = 0; index < (this.length || 0); index++) {
yield this[index];
}
}
console.log([...obj]); // ["zero", "first", "second", "third"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment