Borislav Hadzhiev
Tue Oct 19 2021·2 min read
Photo by Thom Holmes
The "TypeError: map is not a function" occurs when we call the map()
method
on an object 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 the map
method
on valid arrays.
Here is an example of how the error occurs.
const obj = {}; // ⛔️ Uncaught TypeError: map is not a function const result = obj.map(element => { return element + 1; });
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.
const arr = [1, 2, 3]; const result = arr.map(element => { return element + 1; }); console.log(result); // 👉️ [2, 3, 4]
You can conditionally check if the value is an array by using the Array.isArray method.
const arr = 'test'; const result = Array.isArray(arr) ? arr.map(element => element + 1) : []; console.log(result); // 👉️ []
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 an empty array. 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 set = new Set([1, 2, 3]); const result = Array.from(set).map(element => element + 1); console.log(result); // 👉️ [2, 3, 4]
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.
React.js
, you can check if the value is an array before mapping over it in the following way.{Array.isArray(value) ? (value).map(e => /* your code */) : null}
We used a ternary operator to check if the value is an array.
If it is an array, we return the result of calling the map()
method
on it, otherwise we return a null
value.