Borislav Hadzhiev
Last updated: Oct 28, 2021
Check out my new book
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
.
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.
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
.
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);