This article will define the mentioned error and its possible solutions.
How Does “TypeError: object.forEach is not a function in JavaScript” Occur?
When a value that is not an Array, Map, or Set is used, the “forEach()” method such as “Object” and so on, the “TypeError: object.forEach is not a function in JavaScript” occurs. Let’s test the stated cause practically.
Example
In the given example, first, we will create an object with its properties in key-value pair:
name: 'Stephen',
rollno: 11,
subject: 'Commerce'
};
Then, print its properties/entries on the console using the forEach() method:
console.log(o);
});
As you can see in the output, an error is encountered because the forEach method is not applicable for objects:
How to Fix the Specified Error?
To solve the above-discussed error, use Object’s methods such as “Object.keys()” to get keys in an array, “Object.values()” for getting values of the object, or “Object.entries()” for retrieving all the entries of an object. Moreover, the “Array.from()” method converts the specified object into an array of objects.
Let’s try an example to solve this issue.
Example 1: Fix the Mentioned Error Using an Object.entries() Method
In this example, we will get the entries of an object using the “Object.entries()” method with the “forEach()” method that returns an array of object’s entries in key-value pairs:
It will not give an error, because the Object.entries() method converts the values in an array and the forEach() method is used to execute the given function on every element.
The output indicates that the forEach() method is successfully run on the Object using the Object.entries() method:
Note: forEach method is also applied for getting keys and values of an object using the Object.keys() and Object.values() method.
Now, let’s see if you don’t want to get an object’s keys, values, or entries, so what would you do? See the given example!
Example 2: Fix the Mentioned Error Using Array.from() Method
To fix this error, convert the object into an array of objects and then apply the forEach() method on it using the “Array.from()” method. It will print all the properties of an object without giving an error.
Let’s first convert the object into an array of objects:
name: 'Stephen',
rollno: 11,
subject: 'Commerce'
}]
Call the forEach() method:
Output
We have compiled all the best possible solutions to fix the specified error.
Conclusion
The mentioned error occurs when you try to use the “forEach()” method on a value that is not an Array, Set, or Map. To fix this error, use the “Array.from()” method to convert the object to an array and then use the forEach() method on it. This article described the occurrence and solution of the mentioned error.