Deep cloning of any object is very common coding practice for any developer. Java script developers use the cloning everyday in their coding. Here I am going to elaborate the most efficient way to deep clone an object in JavaScript.

Cloning with JSON.parse/JSON.stringify This method is not secure as could result in the data loss.

If you do not use Date, functions, undefinedInfinity, RegExps, Maps, Sets, Blobs, FileLists, ImageDatas, Typed Arrays or other complex types within your object, a very simple one liner to deep clone an object is:

JSON.parse(JSON.stringify(object))

Cloning using the library: this is reliable to use. some of the library methods are

lodash – cloneDeep
AngularJS – angular.copy
Jquery

> jQuery.extend(true, { }, oldObject).clone() only clones DOM elements

Using ES6:

let O1 = {a: "21"};
let O2 = Object.assign({}, O1);
var O3 = {...O1};  // Spread operator

Similar Posts