Deep Clone an Object or Array

Shared by: devcanvas

elixir

1
function deepClone(obj) {
2
  return JSON.parse(JSON.stringify(obj));
3
}
4

5
// Example Usage
6
const original = { a: 1, b: { c: 2 } };
7
const clone = deepClone(original);
8

9
clone.b.c = 42;
10

11
console.log(original.b.c); // 2
12
console.log(clone.b.c);    // 42
13

What It Does

This snippet creates a deep copy of an object or array. A deep copy means that all levels of nested objects or arrays are fully copied, and the new object does not share any references with the original.

For example, in the case of a shallow copy (using Object.assign or the spread operator ...), nested objects still share references between the original and copied objects. This can lead to unexpected changes when modifying nested properties.

The JSON.parse(JSON.stringify(obj)) method ensures that even deeply nested properties are fully copied.


Use Cases

  1. Avoid Unintended Side Effects: When working with state in frameworks like React, Vue, or Svelte, mutating an object directly can lead to unexpected bugs. Deep cloning ensures that the original state remains unchanged.
  2. Data Backup: Before modifying an object or array, you may want to keep a backup copy for potential rollbacks.
  3. Data Processing: When processing complex objects or arrays, deep copies prevent accidental changes to the original structure.

Limitations

Although this method is simple and works well for most JSON-compatible data, there are a few limitations:

  1. Non-JSON-Compatible Data:
    This method only works with data that can be serialized to JSON. Properties like functions, undefined, Infinity, NaN, and special object types (Map, Set, Date, etc.) are not supported. For instance:

    const obj = { date: new Date(), func: () => {} };
    const clone = deepClone(obj);
    console.log(clone); 
    // Output: { date: {}, func: undefined }
  2. Performance Issues:
    For very large objects or arrays, converting to and from JSON can be slow. This method is not optimal for performance-critical applications.

  3. Circular References:
    If the object contains circular references (e.g., an object referring to itself), this method will throw an error:

    const circularObj = {};
    circularObj.self = circularObj;
    
    const clone = deepClone(circularObj); 
    // Throws: "TypeError: Converting circular structure to JSON"

Advanced Alternatives

If you need to handle these limitations, you can use robust third-party libraries such as:

  • Lodash:

    const cloneDeep = require('lodash/cloneDeep');
    const clone = cloneDeep(original);

    Lodash’s cloneDeep is optimized for performance and handles circular references, non-JSON-compatible data, and special objects like Map and Set.

  • Structured Clone API:
    Modern JavaScript browsers support a structured clone method:

    const clone = structuredClone(original);

    This API is faster and more versatile, but it’s not supported in all environments.


Love it? Share it!

DevCanvas DevCanvas Logo

Online Editor with a collection of awesome frontend code and code snippets for developers of all levels.

Legal & Support

Stand with Palestine 🇵🇸! DO NOT BE SILENCED

© 2025 DevCanvas. All rights reserved.