posted 7/16/2011 by Raghav Khunger
Today I was working with my client side code where I needed to do a deep copy of JavaScript object. I found an elegant way to do the same by using $.extend function of jQuery. This function can accept the first argument as boolean type variable which denotes whether we want a deep or shallow copy of an object. We can use it like below:
var myDeepCopyObject = $.extend(true, {}, myObject);
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="http://code.jquery.com/jquery-1.6.2.js" type="text/javascript"></script> </head> <body> </body> <script type="text/javascript"> //Original object var myObject = { a: { b: 1, c: 2 }, d: { e: 3, f: 4 } }; var myDeepCopyObject = $.extend(true, {}, myObject); //Let's test it document.write(myDeepCopyObject === myObject);//false document.write('<br/>'); //Let's change 'b' property in deep copy myDeepCopyObject.a.b = 11; //print it document.write('myDeepCopyObject.a.b: ' + myDeepCopyObject.a.b); // 11 document.write('<br/>'); //Does the original object's 'b' property changed document.write('myObject.a.b: ' + myObject.a.b); //1 </script> </html>
document.write(myDeepCopyObject === myObject);//false
//Let's change 'b' property in deep copy myDeepCopyObject.a.b = 11; //print it document.write('myDeepCopyObject.a.b: ' + myDeepCopyObject.a.b); // 11 document.write('<br/>'); //Does the original object's 'b' property changed document.write('myObject.a.b: ' + myObject.a.b); //1
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18