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


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.

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.

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.

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.

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.

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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee