Borislav Hadzhiev
Thu Oct 28 2021·2 min read
Photo by Duncan Shaffer
To create a deep copy of a Map
:
Map
to an array.JSON.stringify()
method to stringify the array.JSON.parse()
method to parse the JSON.Map()
constructor.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.
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.
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.
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
.
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.