Solve - object.forEach is not a function Error in JS

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

banner

Photo by Diao Darius

Solve - object.forEach is not a function Error #

The "object.forEach is not a function" error occurs because the forEach method is not implemented on objects. To iterate over an object, use the Object.keys() method to get an array of the object's keys and call the forEach() method on the array of keys.

typeerror object foreach is not a function

Here is an example of how the error occurs.

index.js
const obj = { name: 'James', country: 'Chile', }; // โ›”๏ธ TypeError: object.forEach is not a function obj.forEach(element => { console.log(element); });

To solve the error, use the Object.keys method to get an array of the object's keys and call the Array.forEach method on the array.

index.js
const obj = { name: 'James', country: 'Chile', }; // ๐Ÿ‘‡๏ธ ['name', 'country'] console.log(Object.keys(obj)); Object.keys(obj).forEach(key => { console.log(key); // ๐Ÿ‘‰๏ธ name, country console.log(obj[key]); // ๐Ÿ‘‰๏ธ James, Chile });

The Object.keys method returns an array of the object's keys, on which we can call the Array.forEach method.

Note that you can also use the Object.values() method to get an array of the object's values.

index.js
const obj = { name: 'James', country: 'Chile', }; // ๐Ÿ‘‡๏ธ ['James', 'Chile'] console.log(Object.values(obj)); Object.values(obj).forEach(value => { console.log(value); // ๐Ÿ‘‰๏ธ James, Chile });

If you only care about the values of the object, you can get an array of the object's values using the Object.values method and iterate over the array using the Array.forEach method.

If you need the keys and values of an object in an array, you can use the Object.entries method.

index.js
const obj = { name: 'James', country: 'Chile', }; // ๐Ÿ‘‡๏ธ [['name', 'James'], ['country', 'Chile']] console.log(Object.entries(obj)); Object.entries(obj).forEach(([key, value]) => { console.log(key); // ๐Ÿ‘‰๏ธ name, country console.log(value); // ๐Ÿ‘‰๏ธ James, Chile });

The Object.entries method returns an array of arrays, where the inner arrays consist of 2 elements - the key and the value.

We used array destructuring to destructure the key and value from each inner array and used the variables directly in our forEach method.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee