Sometimes, we want to use objects in for of loops with JavaScript.
In this article, we’ll look at how to use objects in for of loops with JavaScript.
How to use objects in for of loops with JavaScript?
To use objects in for of loops with JavaScript, we can use the Object.entries
method.
For instance, we write
const myObject = {
first: "one",
second: "two",
};
for (const [key, value] of Object.entries(myObject)) {
console.log(key, value);
}
to call Object.entries
with myObject
to return an array of myObject
key-value pair arrays.
Then we use the for-of loop and the destructuring syntax to get the key
and value
from each entry.
In it, we log the key
and value
of each pair.
Conclusion
To use objects in for of loops with JavaScript, we can use the Object.entries
method.