Borislav Hadzhiev
Last updated: Apr 28, 2022
Photo from Unsplash
The "TypeError: map is not a function" occurs when we call the map()
method
on a value that is not an array. To solve the error, console.log
the value
you're calling the map()
method on and make sure to only call map
on valid
arrays.
Here is an example of how the error occurs.
const App = () => { const obj = {}; // ⛔️ Uncaught TypeError: map is not a function return ( <div> {obj.map(element => { return <h2>{element}</h2>; })} </div> ); }; export default App;
We called the Array.map() method on an object and got the error back.
To solve the error, console.log
the value you're calling the map
method on
and make sure it's a valid array.
export default function App() { const arr = ['one', 'two', 'three']; return ( <div> {arr.map((element, index) => { return ( <div key={index}> <h2>{element}</h2> </div> ); })} </div> ); }
You can conditionally check if the value is an array by using the Array.isArray method.
const App = () => { const obj = {}; return ( <div> {Array.isArray(obj) ? obj.map(element => { return <h2>{element}</h2>; }) : null} </div> ); }; export default App;
We used a ternary operator, which is very similar to an if/else
statement.
If the value is an array, we return the result of calling the map
method on
it, otherwise we return null
. This way you won't get an error, even if the
value is not an array.
map
method on it.If you have an array-like object which you're trying to convert to an array
before calling the map
method, use the Array.from()
method.
const App = () => { const set = new Set(['one', 'two', 'three']); return ( <div> {Array.from(set).map(element => { return ( <div key={element}> <h2>{element}</h2> </div> ); })} </div> ); }; export default App;
Before calling the map
method, we convert the value to an array. This would
also work for array-like objects like the NodeList
returned from calling the
getElementsByClassName
method.
If you are trying to iterate over an object, use the Object.keys()
method to
get an array of the object's keys on which you can call the map()
method.
export default function App() { const employee = { id: 1, name: 'Alice', salary: 100, }; return ( <div> {/* 👇️ iterate object KEYS */} {Object.keys(employee).map((key) => { return ( <div key={key}> <h2> {key}: {employee[key]} </h2> <hr /> </div> ); })} <br /> <br /> <br /> {/* 👇️ iterate object VALUES */} {Object.values(employee).map((value, index) => { return ( <div key={index}> <h2>{value}</h2> <hr /> </div> ); })} </div> ); }
We used the Object.keys method to get an array of the object's keys.
const employee = { id: 1, name: 'Alice', salary: 100, }; // 👇️ ['id', 'name', 'salary'] console.log(Object.keys(employee)); // 👇️ [1, 'Alice', 100] console.log(Object.values(employee));
We can only call the map()
method on arrays, so we need to either get an array
of the object's keys, or the object's values.