Cloning Javascript Objects

By | 2011/07/21

I have found a way to do this with jQuery:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);
 
// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

More information can be found in the jQuery documentation.

Why would you need it ? Check this example:

var obj1 = {lol : 1},
obj2 = obj1;
 
obj2.lol = 2;
console.log(obj1.lol);//2

The obj2 is a reference to obj1, so all changes you did to the obj2 will be applied on the obj1 as well.