What is the best and most efficient way to deep clone an object in JavaScript?

November 15, 2017 No comments QA JavaScript Cloning Objects

In every programming language sometimes there is a need to have an exact copy of on object. Copy that will be faithful reflection of the base object, with all attributes and fields at every nesting level.

In JavaScript we have several ways to do this:

// our base object
var obj = {a: "hello", c: "test", po: 33, arr: [1, 2, 3, 4], anotherObj: {a: 33, str: "whazzup"}};
json stringify
var obj2 = JSON.parse(JSON.stringify(obj));
lodash deep clone
var obj2 = _.clone(obj, true);
angular copy
var obj2 = angular.copy(obj);
jquery extend
var obj2 = $.extend(true, {}, obj);
Object.assign
var obj2 = Object.assign({}, obj);

Now lets check the performance comparision. Javascript deep copy comparison of solutions

If you want to check this benchmark by yourself, click this link: http://jsben.ch/bWfk9

The most efficient way to deep clone an object in JavaScript is to use Object.assign method.

{{ message }}

{{ 'Comments are closed.' | trans }}