Deep cloning an object in JavaScript involves creating a new object that is a copy of the original object, including all nested properties and objects. There are a few approaches to deep cloning, which are listed below.

Using JSON.parse() and JSON.stringify() (Recommended for most cases)

This method is simple and works well for most objects, but it has some limitations. It can handle primitive values, arrays, plain objects, and objects with properties containing primitive values. However, it cannot handle functions, regular expressions, and objects with circular references.

const originalObject = { a: 1, b: { c: 2, d:[1,2,3,4] } };
const clonedObject = JSON.parse(JSON.stringify(originalObject));

Using libraries like Lodash

Libraries like Lodash provide a deep cloning utility (_.cloneDeep()) that is more robust than the JSON method. Lodash can handle a wider range of objects, including functions and circular references. Lodash’s cloneDeep is generally more memory-intensive than the JSON method, so it might not be as efficient for very large objects or performance-critical scenarios.

const _ = require('lodash');
const originalObject = { a: 1, b: { c: 2, d:[1,2,3,4] } };
const clonedObject = _.cloneDeep(originalObject);

Using structuredClone() global function

structuredClone is a method in JavaScript that allows you to create a deep clone of an object, including various data types like primitives, objects, arrays, and more complex objects like Dates, Maps, Sets, and more. Unlike JSON.parse() and JSON.stringify(), structuredClone is designed to handle a wider range of data types and circular references without issues. The structuredClone method is available in the browser’s context, specifically within the context of a Web Worker or a SharedWorker.

const originalObject = { a: 1, b: { c: 2, d:[1,2,3,4] } };
const clonedObject = structuredClone(originalObject);

For most use cases, the JSON.parse() and JSON.stringify() method is recommended due to its simplicity and widespread compatibility. However, if you need to handle more complex scenarios, a library like Lodash or a custom deep cloning function might be more appropriate.

Support On Demand!

JavaScript