Search
Generic filters

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

By Cronos Editorial Staff on April 9, 2022

function Error in JavaScript

Function Error in JavaScript

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]

				
			

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"]
				
			

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"]
				
			

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"]
				
			

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]
				
			
Hopefully one of these solutions solves your specific case but if not, please leave a comment and we’d be happy to help out.

Articles

Services

Home

About

Contact

2022 Cronos Inc. © ®

Share

function Error in JavaScript

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

Cronos - April 9, 2022

OR SHARE THIS LINK:

				
					https://cronosasia.com/web-design-dev/how-to-fix-object-map-is-not-a-function-error-in-javascript/