Solve - object.map is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Sat Mar 08 19752 min read

Solve - object.map is not a function Error #

The "object.map is not a function" error occurs because the map 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 map() method on the array of keys.

typeerror object map is not a function

Here is an example of how the error occurs.

index.js
const obj = { name: 'James', country: 'Chile', }; // โ›”๏ธ TypeError: object.map is not a function obj.map(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.map method on the array.

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

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

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

index.js
const obj = { num1: 4, num2: 8, }; // ๐Ÿ‘‡๏ธ [4, 8] console.log(Object.values(obj)); const result = Object.values(obj).map(value => { console.log(value); // ๐Ÿ‘‰๏ธ 4, 8 return value * 2; }); // ๐Ÿ‘‡๏ธ [8, 16] console.log(result);

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.map 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)); const result = Object.entries(obj).map(([key, value]) => { console.log(key); // ๐Ÿ‘‰๏ธ name, country console.log(value); // ๐Ÿ‘‰๏ธ James, Chile return {[key]: value}; }); // ๐Ÿ‘‡๏ธ [{name: 'James'}, {country: 'Chile'}] console.log(result);

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 map 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