Tuesday 23 February 2016

Javascript deep copying 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?


Answer



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

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...