Table of Contents
- Parting words
- Other Related Concepts
You will get errors:
map() will give you TypeError: items.map is not a function:
forEach() will give you TypeError: items.forEach is not a function:
for..of will give you TypeError: items are not iterable:
for...in LoopThe most straightforward way to loop through an object's properties is by using the for...in statement. This method works in all modern and old browsers including Internet Explorer 6 and higher.
Here is an example that uses the for...in loop to iterate over an object:
To avoid this problem, you have to explicitly check if the property belongs to the object by using the hasOwnProperty() method:
To overcome this hassle, later in ES8, two other methods were added, Object.entries() and Object.values(). These methods convert the object into an array and then use array looping methods to loop over that array.
Object.keys() MethodBefore ES6, the only way to loop through an object was through using the for...in loop. The Object.keys() method was introduced in ES6 to make it easier to loop over objects.
It takes the object that you want to loop over as an argument and returns an array containing all properties names (or keys).
After which you can use any of the array looping methods, such as forEach(), to iterate through the array and retrieve the value of each property.
Here is an example:
Object.values() MethodThe Object.values() method was introduced in ES8 and it works opposite to that of Object.key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.
Let us look at an example:
Object.entries() MethodThe Object.entries(), an other ES8 method can be used for traversing an array. . Object.entries() outputs an array of arrays, with each inner array having two elements. The first element being the property and the second element is the value.
Here is an example:
To loop over the array returned by Object.entries(), you can either use the for...of loop or the forEach() method as shown below: