Custom objects cannot be iterated over using the
for...of loop. In addition, you can’t use iterator methods like
forEach(). If you do, you’ll get a
TypeError in every instance.
for...in to iterate over objects. This method iterates over all of the object’s enumerable, non-Symbol properties.
In the following example, we use it to iterate over all three properties of
obj, and for each property, we log a string consisting of the property name (ie. its key) and its corresponding value.
var obj = a: 1, b: 2, c: 3; for (const prop in obj) console.log(`obj.$prop = $obj[prop]`); // Output: // "obj.a = 1" // "obj.b = 2" // "obj.c = 3"
We initialized the loop with a variable,
prop, which will hold a different property name (aka key) on each iteration of the object properties. The code specified within the block will run on each iteration.
Here’s a little demo to demonstrate that (click on Result to see the output):
Inside the loop, on every iteration, we log one of the object’s property names and values to the console.
Another way to iterate over an object’s properties is by passing the object inside
Object.entries() and calling the method. This will return all the enumerable properties of that object inside a multidimensional array (array of arrays):
const obj = a: 1, b: 2, c: 3; let result = Object.entries(obj) console.log(result) // [["a", 1], ["b", 2], ["c", 3]]
Then we can loop through that using any of the array iterator methods:
Object.entries(obj).forEach(entry => // do something ) Object.entries(obj).map(entry => // do something ) Object.entries(obj).every(entry => // do something )
You can also use a
for (const entry of Object.entries(obj)) // do something for (const [key, value] of Object.entries(obj)) // do something
Here are some demos:
Here, because we get an array consisting of the key and value on each iteration, we simply access them with
entry respectively. If you want just the keys instead of the key and value, use
Object.keys() in place of
for...of is basically the same: