Back to Snippets
Deep Clone Object
javascript
JavaScript
Create a deep copy of an object, handling nested objects and arrays properly.
Code
1function deepClone(obj) {
2if (obj === null || typeof obj !== "object") {
3return obj;
4}
5
6if (obj instanceof Date) {
7return new Date(obj.getTime());
8}
9
10if (obj instanceof Array) {
11return obj.map(item => deepClone(item));
12}
13
14if (obj instanceof Object) {
15const copy = {};
16Object.keys(obj).forEach(key => {
17copy[key] = deepClone(obj[key]);
18});
19return copy;
20}
21}
22
23// Usage
24const original = { a: 1, b: { c: 2 } };
25const cloned = deepClone(original);Details
Language
javascript
Category
JavaScript