Create a deep copy of an object without references
1function deepClone(obj) {
2 // Handle null and non-object types
3 if (obj === null || typeof obj !== 'object') {
4 return obj;
5 }
6
7 // Handle Date
8 if (obj instanceof Date) {
9 return new Date(obj.getTime());
10 }
11
12 // Handle Array
13 if (Array.isArray(obj)) {
14 return obj.map(item => deepClone(item));
15 }
16
17 // Handle Object
18 const clonedObj = {};
19 for (const key in obj) {
20 if (obj.hasOwnProperty(key)) {
21 clonedObj[key] = deepClone(obj[key]);
22 }
23 }
24
25 return clonedObj;
26}
27
28// Usage example
29const original = { name: 'John', details: { age: 30 } };
30const copy = deepClone(original);
31copy.details.age = 31;
32console.log(original.details.age); // 30 (unchanged)Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.