Javascript 克隆/复制 Map 实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8206988/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clone/copy a Map instance
提问by sazr
How do I clone/copy a map in JavaScript?
如何在 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();
采纳答案by rob
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]
注意:newMap[i] 很可能是对与 myMap[i] 相同对象的引用
回答by tswaters
With the introduction of Maps in JavaScript it's quite simple considering the constructor accepts an iterable:
随着 JavaScript 中 Maps 的引入,考虑到构造函数接受一个可迭代对象,这非常简单:
var newMap = new Map(existingMap)
Documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
此处的文档:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
回答by Joshua Michael Waggoner
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()
克隆地图非常简单,因为您所谈论的只是一个对象。Map
在 ES6 中有一个你应该查找的,但是要复制一个对象,只需使用Object.assign()
let map = {"a": 1, "b": 2}
let copy = Object.assign({}, map);
You can also use cloneDeep()
from Lodash
您也可以cloneDeep()
从 Lodash使用
let copy = cloneDeep(map);
回答by Pastor Bones
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.
JQuery 有一个方法来扩展一个对象(合并两个对象),但是这个方法也可以通过提供一个空对象来克隆一个对象。
// Shallow copy
var newObject = jQuery.extend({}, oldObject);
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);
More information can be found in the jQuery documentation.
更多信息可以在jQuery 文档中找到。
回答by alex
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.
要么使用经过良好测试的递归属性复制器,要么如果性能不是问题,则序列化为 JSON 并再次解析为新对象。
回答by Nicole
There is no built-in clone/copy. You can write your own method to either shallow or deep copy:
没有内置的克隆/复制。您可以将自己的方法编写为浅拷贝或深拷贝:
function shallowCopy(obj) {
var result = {};
for (var i in obj) {
result[i] = obj[i];
}
return result;
}
function deepCopy(obj) {
var result = {};
for (var i in obj) {
// recursion here, though you'll need some non-trivial logic
// to avoid getting into an endless loop.
}
return result;
}
All objects in Javascript are dynamic, and can be assigned new properties. A "map" as you refer to it is actually just an empty object. An Array is alsoan object, with methods such as slice
and properties like length
.
Javascript 中的所有对象都是动态的,并且可以分配新的属性。您所指的“地图”实际上只是一个空对象。Array也是一个对象,具有诸如 之slice
类的方法和属性length
。
回答by robdc
If you need to make a deep copy of a Map you can use the following:
如果您需要制作 Map 的深层副本,您可以使用以下方法:
new Map(JSON.parse(JSON.stringify(Array.from(source))));
Where source
is the original Map object.
source
原始 Map 对象在哪里。
Note this may not be suitable for all use cases where the Map values are not serializable, for more details see: https://stackoverflow.com/a/122704/10583071
请注意,这可能不适用于 Map 值不可序列化的所有用例,有关更多详细信息,请参见:https: //stackoverflow.com/a/122704/10583071
回答by Dmitriy Pichugin
I noticed that Map should require special treatment, thus with all suggestions in this thread, code will be:
我注意到 Map 应该需要特殊处理,因此在这个线程中的所有建议中,代码将是:
function deepClone( obj ) {
if( !obj || true == obj ) //this also handles boolean as true and false
return obj;
var objType = typeof( obj );
if( "number" == objType || "string" == objType ) // add your immutables here
return obj;
var result = Array.isArray( obj ) ? [] : !obj.constructor ? {} : new obj.constructor();
if( obj instanceof Map )
for( var key of obj.keys() )
result.set( key, deepClone( obj.get( key ) ) );
for( var key in obj )
if( obj.hasOwnProperty( key ) )
result[key] = deepClone( obj[ key ] );
return result;
}
回答by Shubham Kumar
A new and elegant way of doing this:
一种新的优雅的方式来做到这一点:
var map1 = {"a": "b"};
var map2 = {...map1};