How to create a Deep Copy of a Map in JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

Create a Deep Copy of a Map in JavaScript #

To create a deep copy of a Map:

  1. Convert the Map to an array.
  2. Use the JSON.stringify() method to stringify the array.
  3. Use the JSON.parse() method to parse the JSON.
  4. Pass the result to the Map() constructor.
index.js
const existingMap = new Map([ ['address', {street: 'Example'}], ['numbers', [1, 2, 3]], ]); const deepCopy = new Map(JSON.parse( JSON.stringify(Array.from(existingMap)) )); // ๐Ÿ‘‡๏ธ {'address' => {street: 'Example'}, 'numbers': [1, 2, 3]} console.log(deepCopy);

We used the Array.from method to convert the Map into a two dimensional array.

index.js
const existingMap = new Map([ ['address', {street: 'Example'}], ['numbers', [1, 2, 3]], ]); // ๐Ÿ‘‡๏ธ [['address', {street: 'Example}], ['numbers', [1, 2, 3]]] console.log(Array.from(existingMap));

The next step is to use the JSON.stringify method to convert the array to a JSON string.

This makes all the nested arrays and objects lose their reference.

We then used the JSON.parse method to parse the string back into an array.

The last step is to pass the two dimensional array to the Map() constructor.

The trick here is to stringify the array, using the JSON.stringify method, so that all nested objects lose their reference.

If we then try to mutate the array in the new Map, it wouldn't affect the existing Map.

index.js
const existingMap = new Map([ ['address', {street: 'Example'}], ['numbers', [1, 2, 3]], ]); const deepCopy = new Map(JSON.parse( JSON.stringify(Array.from(existingMap)) )); deepCopy.get('numbers').pop(); // ๐Ÿ‘‡๏ธ {'address' => {street: 'Example'}, 'numbers' => [1, 2]} console.log(deepCopy); // ๐Ÿ‘‡๏ธ {'address' => {'street':'Example'},'numbers' => [1, 2, 3]} console.log(existingMap);

We used the pop method to mutate the array in the deep copy, however the array in the existing Map wasn't affected.

The nested arrays in the Maps have a different reference and location in memory, because we used the JSON.stringify method.

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