Javascript deep copying object

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

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:

    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.

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

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

Gist: Library agnostic version of jQuery's Extend

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.

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

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


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.

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];
      }
   }
}
链接地址: http://www.djcxy.com/p/6944.html

上一篇: 克隆对象TypeScript

下一篇: Javascript深拷贝对象