Middle
What methods exist for creating a deep copy of an object?
sobes.tech AI
Answer from AI
There are several approaches to creating a deep copy of an object in JavaScript:
- JSON.parse(JSON.stringify(obj)) — the simplest method, but it does not copy functions, symbols, properties with undefined, and does not work with objects containing cyclic references.
const deepCopy = JSON.parse(JSON.stringify(originalObject));
-
Recursive copying — write a function that recursively copies all nested objects and arrays, considering data types.
-
Using libraries — for example, lodash with the
_.cloneDeep()function:
const _ = require('lodash');
const deepCopy = _.cloneDeep(originalObject);
- Structured Clone API — a modern method supported in browsers and Node.js, which correctly copies most types, including cyclic references:
const deepCopy = structuredClone(originalObject);
The choice of method depends on data type requirements and environment.