[Javascript] Iterate over Object
const [a, b] = {
a: 3,
b: 4,
};
console.log(a, b); // TypeError: {(intermediate value)(intermediate value)} is not iterable
How to make it work without touch original code?
We need to use [Symbol.iterator]
for Object.prototype
;
Object.prototype[Symbol.iterator] = function() {
const values = Object.values(this)
let index = 0
const len = values.length
return {
next() {
return {
value: values[index++],
done: index <= len ? false: true
}
}
}
}
const [a, b] = {
a: 3,
b: 4,
};
console.log(a, b);
We can improve this version by knowing const values = Object.values(this)
is already a iterable.
Object.prototype[Symbol.iterator] = function() {
const values = Object.values(this)
return values[Symbol.iterator]()
}
const [a, b] = {
a: 3,
b: 4,
};
console.log(a, b);
We can improve this version by using generator.
Object.prototype[Symbol.iterator] = function* () {
yield* Object.values(this);
};
const [a, b] = {
a: 3,
b: 4,
};
console.log(a, b);