Search⌘ K

Restricted Deep Copy Implementations

Explore how to perform deep copies of JavaScript objects using JSON and jQuery extend methods. Understand their limitations, what is lost during cloning, and why refactoring might be a better solution when cloning complex objects. This lesson helps you grasp the nuances of cloning to write more reliable JavaScript code.

JSON methods

There is a very easy implementation for making deep copies of JavaScript objects. Convert the JavaScript object into a JSON string, then convert it back into a JavaScript object.

Node.js
a = [];
a.b = 'language hack';
//comment the above a.b = 'language hack' and uncomment below line
//a = new Date(2011,0,1);
var deepCopy = function( o ) {
return JSON.parse(JSON.stringify( o ));
}
var cloned_a = deepCopy( a );
console.log( 'cloned_a.b = ', cloned_a.b );
//comment the line 9 and uncomment the below line to see the output of line 4
//console.log( 'cloned_a = ', cloned_a );

Restrictions:

  • Object o has to be finite; otherwise, JSON.stringify throws an error.

  • The JSON.stringify conversion has to be lossless. Therefore, methods not allowed as members of type function are ignored by the JSON stringifier. The undefined value is not allowed either. Object ...