...

/

Restricted Deep Copy Implementations

Restricted Deep Copy Implementations

Learn about two methods to implement deep copy and their limitations.

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.

Press + to interact
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 ...