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

August 16, 2019 No comments QA JavaScript Cloning Objects

1. Introduction

In every programming language sometimes there is a need to have an exact copy of on object. Copy that will be a 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"}};

2. Using JSON stringify function

var obj2 = JSON.parse(JSON.stringify(obj));

3. Using lodash deep clone method

var obj2 = _.clone(obj, true);

4. For Angular framework use angular.copy function

var obj2 = angular.copy(obj);

5. Using jQuery extend function

var obj2 = $.extend(true, {}, obj);

6. Using Object.assign

var obj2 = Object.assign({}, obj);

7. Performance comparision

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

7. Conclusion

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

{{ message }}

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