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?
According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object. assign supports only shallow copy.
Copy an Object With Object. assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.
Like most other programming languages JavaScript allows supports the concept of deep copy and shallow copy. Shallow Copy: When a reference variable is copied into a new reference variable using the assignment operator, a shallow copy of the referenced object is created.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With