Sobes.tech
Middle

How to make a deep copy of an object? Tell me about structured clone, JSON.stringify, lodash cloneDeep — what are the differences?

sobes.tech AI

Answer from AI

Deep copying an object involves creating a new data structure that is completely independent of the original, including nested objects.

JSON.stringify / JSON.parse — the simplest way to deep copy, but with limitations:

  • Does not copy functions, undefined, symbols, properties with Symbol type.
  • Does not work with objects containing cyclic references (will throw an error).
  • Converts dates to strings.
const copy = JSON.parse(JSON.stringify(original));

_.cloneDeep (lodash) — a universal method for deep copying, which:

  • Copies almost all data types, including nested objects and arrays.
  • Handles cyclic references.
  • Does not copy functions (they remain references).
import _ from 'lodash';
const copy = _.cloneDeep(original);

structuredClone — a modern built-in method for deep cloning, supported in browsers and Node.js:

  • Works with most data types, including Map, Set, Date, RegExp.
  • Supports cyclic references.
  • Does not copy functions and some special objects (e.g., DOM elements).
  • Faster and more reliable than the JSON method.
const copy = structuredClone(original);

Summary:

  • For simple objects without functions and cycles, JSON can be used.
  • For complex structures with cycles and various types — lodash cloneDeep or structuredClone.
  • structuredClone is the preferred modern method if environment support allows.