Javascript 深度复制对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11299284/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:22:04  来源:igfitidea点击:

Javascript deep copying object

javascriptobject

提问by Matteo Pagliazzi

Possible Duplicate:
What is the most efficient way to clone a JavaScript object?

可能的重复:
克隆 JavaScript 对象的最有效方法是什么?

I have an object like this:

我有一个这样的对象:

User = {    
  name: "user",
  settings: {
    first: "1",
    second: "2"    
  }    
}

and a second one:

第二个:

user1 = {
  name: "user1",
  settings: {
    second: "3"
  }
}

now I want to copy user1's custom values into User, using:

现在我想将 user1 的自定义值复制到 User 中,使用:

    for(var key in user1){
        User[key] = user1[key];
    }

the result User will be:

结果用户将是:

User = {
  name: "user1",
  settings: {
    second: "3"
  }
}

User.settings has been entirely replace while I wanted only settings.second to be replaced.

User.settings 已完全替换,而我只想替换 settings.second。

How to achieve this, without knowing how much child object the main object have?

在不知道主对象有多少子对象的情况下,如何实现这一点?

采纳答案by Matteo Pagliazzi

I've found that the best way to go is this:

我发现最好的方法是这样的:

http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/

http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/

Object.deepExtend = function(destination, source) {
  for (var property in source) {
    if (typeof source[property] === "object" &&
     source[property] !== null ) {
      destination[property] = destination[property] || {};
      arguments.callee(destination[property], source[property]);
    } else {
      destination[property] = source[property];
    }
  }
  return destination;
};


Object.extend(destination, source);

What about this?

那这个呢?

    function clone(destination, source) {
        for (var property in source) {
            if (typeof source[property] === "object" && source[property] !== null && destination[property]) { 
                clone(destination[property], source[property]);
            } else {
                destination[property] = source[property];
            }
        }
    };

回答by Jon Jaques

Grabbed jQuery's extend method, and made it library agnostic.

抓住了 jQuery 的扩展方法,并使它与库无关。

Gist: Library agnostic version of jQuery's Extend

要点:jQuery 扩展的库不可知版本

Its wrapped in an Extender constructor, so you don't have to instantiate all of its internal methods each time you call the extend method.

它包含在 Extender 构造函数中,因此您不必在每次调用扩展方法时实例化其所有内部方法。

Disclaimer: I have not tested this extensively. It's basically a 1:1 clone of jQuery's extend(), however your mileage may vary.

免责声明:我没有对此进行广泛的测试。它基本上是 jQuery 的扩展()的 1:1 克隆,但是您的里程可能会有所不同。

Use it like this.

像这样使用它。

var user1 = {
  name: "user1",
  settings: {
    first: "1",
      second: {bar: 'foo'}
  }
};
var user2 = {
  name: "user2",
  settings: {
    second: {foo:'bar'}
  }
};

/* merge user1 into User */
__extend(true, user1, user2);

// Modifies the User object
user1.settings.second.foo == 'bar'; // true

// note, you can do assignment too.
var newUser = __extend(true, user1, user2);

See here for more documentation

请参阅此处获取更多文档

回答by Phillip Whisenhunt

This is really hacky, but this should work. I suggest doing as the other users have suggested in the comments; find a pre-existing library that will do this for you.

这真的很hacky,但这应该有效。我建议按照其他用户在评论中的建议进行操作;找到一个预先存在的库来为你做这件事。

for(var key in user1){  
   var temp = User[key]
   User[key] = user1[key];   
   for(var key1 in temp){
      if(User[key][key1] == null){
         User[key][key1] = temp[key1];
      }
   }
}