How to create a shallow Copy of a Map in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20211 min read

Create a shallow Copy of a Map in JavaScript #

To create a shallow copy of a Map, pass the existing Map as a parameter to the Map() constructor, e.g. const newMap = new Map(oldMap). The Map() constructor takes an iterable, such as another Map, and adds the key-value pairs to the new Map.

index.js
const oldMap = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); // ๐Ÿ‘‡๏ธ {'name' => 'Tom', 'country' => 'Chile'} console.log(oldMap); const copy = new Map(oldMap); // ๐Ÿ‘‡๏ธ {'name' => 'Tom', 'country' => 'Chile'} console.log(copy);

We used the Map() constructor to create a shallow copy of an existing Map.

The only parameter the constructor takes is an iterable, such as an array, or another Map.

The elements in the iterable should be key-value pairs, e.g. a two dimensional array or another Map object.

index.js
const example1 = [ ['name', 'Tom'], ['country', 'Chile'], ]; const example2 = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]);

Each key-value pair gets added to the new Map.

The new Map object has a completely different reference and location in memory. Adding key-value pairs to it does not interact with the existing Map.

index.js
const oldMap = new Map([ ['name', 'Tom'], ['country', 'Chile'], ]); // {'name' => 'Tom', 'country' => 'Chile'} console.log(oldMap); const copy = new Map(oldMap); // ๐Ÿ‘‡๏ธ {'name' => 'Tom', 'country' => 'Chile'} console.log(copy); copy.set('age', 30); // ๐Ÿ‘‡๏ธ {'name' => 'Tom', 'country => 'Chile', 'age' => 30} console.log(copy); // ๐Ÿ‘‡๏ธ {'name' => 'Tom', 'country => 'Chile'} console.log(oldMap);

Further Reading #

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