How Do I Copy a Map into a Duplicate Map? [duplicate]
Solution 1:
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
Solution 2:
A simple way (to do a shallow copy) is to copy each property of the source map to the target map:
var newMap = {};
for (var i in myMap)
newMap[i] = myMap[i];
NOTE: newMap[i] could very well be a reference to the same object as myMap[i]
Solution 3:
Very simple to clone a map since what you're talking about is just an object. There is a Map
in ES6 that you should look up, but to copy an object, just use Object.assign()
let map = {"a": 1, "b": 2}
let copy = Object.assign({}, map);
You can also use cloneDeep()
from Lodash
let copy = cloneDeep(map);