Iterating over Object properties in JavaScript
There are several ways to iterate over an object’s properties in JavaScript.
Object.entries() returns an array of object’s own enumerable string-keyed property [key, value]
pairs. This array can then be iterated over using forEach() or for…of.
Example
Output
Similarly, for...of
can also be used with Object.entries()
.
for…in
for...in
statement can also be used to iterate over object properties, but it also iterates over inherited properties. Luckily, hasOwnProperty() method can be used to check if a property is object’s own property.
Object.keys() and Object.values()
If we are only concerned with object property keys, then Object.keys()
can be used. Similarly, Object.values()
can be used to get object property values.