1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| function deepClone(source) { if(typeof source !== "object" || source == null){ return source; } const target = Array.isArray(source) ? [] : {}; for(const key in source){ if( typeof source[key] === "object" && source[key] !== null){ target[key] = deepClone(source[key]); } else { target[key] = source[key]; } } return target; }
const original = { number: 123, string: "hello", array: [1,2,3], obj: { prop1: "test", prop2: { nested: "test2", }, }, };
const cloned = deepClone(original);
console.log(cloned);
|