Javascript 深度复制对象 [英] Javascript deep copying object

查看:36
本文介绍了Javascript 深度复制对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有一个这样的对象:

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

还有第二个:

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

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

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

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

结果用户将是:

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

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

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

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

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

推荐答案

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

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

http://andrewdupont.net/2009/08/28/deep-在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);

这个怎么样?

    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];
            }
        }
    };

这篇关于Javascript 深度复制对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆