isotropic-2022
Share
Blog
Search
Menu

How To Fix object.map is not a function Error in JavaScript

By Greg Murray
|
Last updated on April 8th, 2022
|

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.

object-map-is-not-a-function-image

What happened, and why are you seeing this object.map is not a function error? Read on to find out.

The Problem

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.

💡

Creating a new array from a given array is a way to maintain immutability in your JavaScript code. It is important to note that if you are using Array.map() on an array of objects and change a property on a given object, that object has now been mutated. To avoid this you can create a copy of the object first and then modify the copy.

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:

const items = [1, 2, 3];

// ES5 approach
const doubledItems = items.map(function (item) {
  return item * 2;
});

// ES6+ approach
const doubledItems = items.map((item) => {
  return item * 2;
});

// Least code approach
const doubledItems = items.map((item) => item * 2);

console.log(doubledItems); // [2, 4, 6]Code language: JavaScript (javascript)

The Solution

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:

const object = {
  items: [
    {
      id: 1,
      data: "item 1 data",
    },
    {
      id: 2,
      data: "item 2 data",
    },
  ],
};

const error = object.map((item) => item.data); // ❌ This will cause your error!

// Instead, map over the items property rather than the parent object
const result = object.items.map((item) => item.data);

console.log(result); // ["item 1 data", "item 2 data"]Code language: JavaScript (javascript)

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:

const object = {
  1: {
    id: "1",
    data: "item 1 data",
  },
  2: {
    id: "2",
    data: "item 2 data",
  },
};

const error = object.map((item) => item.data); // ❌ This will cause your error!

// Get an array of the keys in your object
const array = Object.keys(object); // [1, 2]

// Loop through that array using each key to get the value
const result = array.map((key) => {
  const value = object[key];

  // Perform your desired logic here then return a new value
  return value.data;
});

console.log(result); // ["item 1 data", "item 2 data"]Code language: JavaScript (javascript)

Another common solution is needed when you are working with a JavaScript Set or Map . Because these are both iterable and even have a .forEach() method you may reasonably assume .map() would also work. Since they are not technically arrays, though, you will need a workaround. The solution is similar for both a Set or a Map and we even have an article that explains how to work with their values in more detail which you can view here.

// --- Map solution example ---

const myMap = new Map();
myMap.set(1, "item 1 data");
myMap.set(2, "item 2 data");

const myMapError = myMap.map(); // ❌ This will cause your error!

// Create an array from the values of the Map
const myMapArray = [...myMap.values()];

const myMapResult = myMapArray.map((item) => {
  // Perform your logic here
  if (item) {
    return item;
  }
});

console.log(myMapResult); // ["item 1 data", "item 2 data"]

// --- Set solution example ---

const mySet = new Set();

mySet.add("item 1 data");
mySet.add("item 2 data");

// Since set values are unique this won't be added to the Set
mySet.add("item 2 data");

const mySetError = mySet.map(); // ❌ This will cause your error!

const mySetArray = [...mySet.values()];

const mySetResult = mySetArray.map((item) => {
  // Perform your logic here
  if (item) {
    return item;
  }
});

console.log(mySetResult); // ["item 1 data", "item 2 data"]Code language: JavaScript (javascript)

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:

const safelyMap = (data, callback) => {
  if (!(data && Array.isArray(data))) {
    return [];
  }

  return data.map(callback);
};

// Arbitrary callback function
const callback = (item) => item;

console.log(safelyMap(null, callback)); // []
console.log(safelyMap(new Set(), callback)); // []
console.log(safelyMap([1, 2, 3], callback)); // [1, 2, 3]Code language: JavaScript (javascript)

Hopefully one of these solutions solves your specific case but if not, please leave a comment and we’d be happy to help out.

The Isotropic Codex is a collection of code snippets and education for WordPress, web and WooCommerce developers.
References
Subscribe & Share
If you liked this content, subscribe for our monthly roundup of WordPress news, website inspiration, exclusive deals and interesting articles.
Unsubscribe at any time. We do not spam and will never sell or share your email.
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Milind
Milind
1 year ago

Hey,

Thank you for sharing this article; it is very helpful to me.

Article By
Greg Murray
Contributors/Editors
notloggedin
I’m a passionate and driven web developer with an eye for design and appreciation for the human aspect of technology. I am experienced with building websites for small to medium businesses or large web applications for big businesses. Websites can be custom made using cutting edge technology and responsive design or created using the website builder of your choice.
We're looking for new authors. Explore Isotropic Jobs.
linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram