Skip to content

Instantly share code, notes, and snippets.

@ScottRudiger
Last active January 19, 2018 04:30
Show Gist options
  • Save ScottRudiger/5029fd382e24037a28026b2822c0cbcc to your computer and use it in GitHub Desktop.
Save ScottRudiger/5029fd382e24037a28026b2822c0cbcc to your computer and use it in GitHub Desktop.
Make a JavaScript Object Iterable
const makeIterable = obj => Object.defineProperty(obj, Symbol.iterator, {
writable: true,
value: function*() {
const values = Object.values(obj);
for (let value of values) {
yield value;
}
},
});
const obj = makeIterable({
a: 1,
b: 2,
c: 3,
});
// now JavaScript constructs that make use of the iteration protocol can be used with obj:
// for..of
for (let value of obj) {
console.log(value);
}
// 1
// 2
// 3
// destructuring assignment
[a, b, c] = obj;
console.log(c); // 3
// spread syntax
const arr = [...obj];
console.log(arr); // [1, 2, 3]
// using Object.defineProperty, the enumerable property defaults to false; therefore, Symbol.iterator won't show up when logging obj:
console.log(obj); // {a: 1, b: 2, c: 3}
// set Symbol.iterator using normal assignment or set enumerable to true and you'll get:
console.log(obj); /*
{
a: 1,
b: 2,
c: 3,
[Symbol(Symbol.iterator)]: [GeneratorFunction]
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment