Introduction

What is the best way to clone a JavaScript object? We have seen some recursive copying function with various flaws. But, what is the best way to clone an object in JavaScript?

Solution 1 - Use jQuery $.extend()

If you wish to have a fast object clone, you can use jQuery $.extend().

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

Note: the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (for example: trying to deep extend a DOM element). It's used frequently in jQuery core and in plugins to great effect. More information can be found in the jQuery documentation.

Solution 2 - Use stringify() and parse()

Assuming that you have only variables and not any functions or Date in your object, you can just use:

var newObject = JSON.parse(JSON.stringify(oldObject));

Above solution is the better than deep copy an object (it beats out JQuery.extend with deep flag set true by 10-20%).

Note: Beware using the JSON.parse(JSON.stringify(obj)) method on Date objects - JSON.stringify(new Date()) returns a string representation of the date in ISO format, which JSON.parse() doesn't convert back to a Date object.