Imagine this: you’ve got your API call setup and working. The data comes back with what you expected. Now? Time to work with that data to create the solution you are looking for. All of a sudden, you see an error in your console.
What happened, and why are you seeing this object.map is not a function error? Read on to find out.
The cause of your error is actually quite simple: the .map() method is only applicable when working with arrays. More specifically, the method exists on the Array prototype as Array.prototype.map().
This method was originally introduced in 2009 with ES5 and is very useful in many scenarios. Array.map() takes a callback function as its one and only parameter. That callback is given two parameters: the current item and its index in the array. The method itself works similar to calling Array.forEach() except the return values of the callback are put together into a new array which is returned by the method itself.
For example, if you have an array of numbers and want to create a new array where each number in the original array is doubled, you could simply do this:
To solve the
object.map is not a function error, first figure out the shape of the data you are working with and then create an array from that data depending on what the data is. For example, maybe your data is a simple object but the array you were looking for is actually inside that object. In that case, just use dot notation to access the desired property:
It is also possible that your data is a simple object but the data you would like to iterate over is stored in each key of the object. In that case you could loop through those keys and perform your logic on each key’s respective value:
If you want to avoid the error in the future, especially if you don’t know the exact shape of the data you will be trying to call Array.map() on, here is a simple function to safely map an array’s values:
Hopefully one of these solutions solves your specific case but if not, please leave a comment and we’d be happy to help out.