Borislav Hadzhiev
Last updated: Jul 25, 2022
Check out my new book
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.
Here is an example of how the error occurs.
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.
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.
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);
Object.values
method. Then you can iterate over the array using the Array.map
method.If you need the keys and values of an object in an array, use the Object.entries method.
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.