Is it possible to loop through the properties in a JavaScript object? For instance, I have a JavaScript object defined as this:
myObject.options = {
property1:
In ES6, it is also possible to iterate over the values of an object using the for..of
loop. This doesn't work right out of the box for JavaScript objects, however, as you must define an @@iterator property on the object. This works as follows:
for..of
loop asks the "object to be iterated over" (let's call it obj1 for an iterator object. The loop iterates over obj1 by successively calling the next() method on the provided iterator object and using the returned value as the value for each iteration of the loop.Here is an example:
const obj1 = {
a: 5,
b: "hello",
[Symbol.iterator]: function() {
const thisObj = this;
let index = 0;
return {
next() {
let keys = Object.keys(thisObj);
return {
value: thisObj[keys[index++]],
done: (index > keys.length)
};
}
};
}
};
Now we can use the for..of
loop:
for (val of obj1) {
console.log(val);
} // 5 hello