Middle+
How to perform deep copying of objects in JavaScript?
sobes.tech AI
Answer from AI
Deep copying of objects in JavaScript means creating a new copy of an object with all nested objects, rather than just copying references.
The simplest way is to use JSON.parse(JSON.stringify(obj)), but it does not copy functions, dates, undefined, and other special types.
For more universal deep copying, you can write a recursive function or use libraries like lodash (_.cloneDeep).
Example of a simple recursive deep copy function:
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) {
return obj.map(deepClone);
}
const cloned = {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
cloned[key] = deepClone(obj[key]);
}
}
return cloned;
}
const original = { a: 1, b: { c: 2 } };
const copy = deepClone(original);
copy.b.c = 3;
console.log(original.b.c); // 2 — original remains unchanged
This approach works for simple objects without cyclic references.