I am currently reading about Symbols and Iterators (ES6 features) and after running into an example there, I am trying to make an object iterable so that I can use for...of
feature. From few examples/answers here/articles I checked, it looks like this in plain case:
let obj = {
prop1: 5,
prop2: 'test',
prop3: new Date(),
[Symbol.iterator]: () => ({
items: obj.items,
next: function next() {
return {
done: this.items.length === 0,
value: this.items.shift()
}
}
})
};
Object.defineProperty(obj, "items", {
enumerable: false,
get: function() {
let props = [];
for(let prop in this) if(this.hasOwnProperty(prop)) props.push(this[prop]);
return props;
}
});
for(let prop of obj) console.log(prop);
But I find it annoying to list manually all the values of an object's properties in items
array of iterator. Also it feels dirty and messy with Object.defineProperty
. I am kind of trying tom expand the example from the link. Is there a smarter/simpler way to get all the object's properties inside iterator (instead of items: obj.items
and related bloat or manually listing items like items: [5, 'test', new Date()]
)?