Solve - Map.get is not a function Error in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20212 min read

Solve - Map.get is not a function Error #

The "Map.get is not a function" error occurs when we call the get() method on a value that is not a Map object. To solve the error, convert the value to a Map before calling the get method or make sure to only call the method on Map objects.

typeerror map get is not a function

Here is an example of how the error occurs.

index.js
const map = {}; // ⛔️ TypeError: map.get is not a function const result = map.get('name');

We called the Map.get method on an object and got the error back.

To solve the error, make sure to only call the get method on Map objects.

index.js
const map = new Map([ ['name', 'Tim'], ['country', 'Chile'], ]); console.log(map.get('name')); // 👉️ Tim console.log(map.get('test')); // 👉️ undefined

Alternatively, you can check if the object is a Map by using the instanceof operator.

index.js
const map = new Map([ ['name', 'Tim'], ['country', 'Chile'], ]); if (map instanceof Map) { const result = map.get('name'); console.log(result); // 👉️ "Tim" }

The instanceof operator allows us to check if an object was created using the Map() constructor.

index.js
const map = new Map([ ['name', 'Tim'], ['country', 'Chile'], ]); console.log([] instanceof Map); // 👉️ false console.log({} instanceof Map); // 👉️ false console.log(map instanceof Map); // 👉️ true

If you need to convert an object to a Map, you can use the Object.entries method.

index.js
const obj = { id: 1, name: 'James', }; // ✅ Convert Object to Map const map1 = new Map(Object.entries(obj)); console.log(map1); // 👉️ {'id' => 1, 'name' => 'James'} // ✅ Convert Map to Object const objAgain = Object.fromEntries(map1); console.log(objAgain); // 👉️ {id: 1, name: 'James'}

We can pass an array of arrays to the Map constructor to create a Map. Each nested array should contain 2 elements - a key and a value.

Use the search field on my Home Page to filter through my more than 1,000 articles.