How Do I Copy A Map Into A Duplicate Map?
Solution 1:
With the introduction of Maps in JavaScript it's quite simple considering the constructor accepts an iterable:
var newMap = newMap(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);
Solution 4:
JQuery has a method to extend an object (merging two objects), but this method can also be used to clone an object by providing an empty object.
// Shallow copyvar newObject = jQuery.extend({}, oldObject);
// Deep copyvar newObject = jQuery.extend(true, {}, oldObject);
More information can be found in the jQuery documentation.
Solution 5:
There is nothing built in.
Either use a well tested recursive property copier or if performance isn't an issue, serialise to JSON and parse again to a new object.
Post a Comment for "How Do I Copy A Map Into A Duplicate Map?"