How Do I Copy a Map into a Duplicate Map?

sazr picture sazr · Nov 21, 2011 · Viewed 116.6k times · Source

How do I clone/copy a map in JavaScript?

I know how to clone an array but how do I clone/copy a map?

var myArray = new Array(1, 2, 3);
var copy    = myArray.slice();
// now I can change myArray[0] = 5; & it wont affect copy array

// Can I just do the same for map?
var myMap = new ?? // in javascript is it called a map?
var myMap = {"1": 1, "2", 2};
var copy  = myMap.slice(); 

Answer

tswaters picture tswaters · Apr 4, 2016

With the introduction of Maps in JavaScript it's quite simple considering the constructor accepts an iterable:

var newMap = new Map(existingMap)

Documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map