简体   繁体   English

如何深度复制包含集合的JavaScript对象

[英]How to deep copy a JavaScript object that contains a set

jQuery deep copy using jQuery深拷贝使用
var objCopy = jQuery.extend(true, {}, obj);

works well for 效果很好
var obj = {str: "text", num: 2, arr: [1, 2, 3]}

but what about for 但是呢
var obj = {str: "text", num: 2, set: new Set([1,2,3])} ? var obj = {str: "text", num: 2, set: new Set([1,2,3])}

I've found that making changes to obj.set also changes objCopy.set . 我发现对obj.set进行更改也会改变objCopy.set
Is there a way to drill down to the set inside obj and assign a deep copy of that to objCopy ? 有没有办法深入到obj的集合并将其深层副本分配给objCopy

You can implement a small copy function that will handle it when there is a set. 您可以实现一个小型copy功能,当有一个集合时将处理它。

function myCopy(obj) {
  obj = jQueryDeepCopierOfObject(obj); // Deep copy it here

  for (let prop in obj)
    if (obj.hasOwnProperty(prop))
      if (Set.prototype.isPrototypeOf(obj[prop]))
        obj[prop] = new Set(obj[prop]);

  // hoping there won't be any object in the set.
  return obj;
}

EXAMPLE: 例:

 var a = { a: "foo", b: "bar", c: "baz", set: new Set() }; a.set.add("fox"); a.set.add("bat"); a.set.add("wisdom"); var b = mycopy(a); console.log("a === b: ", a === b); // → false console.log("a.set === b.set: ", a.set === b.set); // → false b.set.add("kindness"); console.log("set a has kindness: ", a.set.has("kindness")); // → false console.log("set b has kindness: ", b.set.has("kindness")); // → true function mycopy(obj) { obj = Object.assign({}, obj); for (let prop in obj) if (obj.hasOwnProperty(prop)) if (Set.prototype.isPrototypeOf(obj[prop])) obj[prop] = new Set(obj[prop]); return obj; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM