The problem
Need to copy an object where modifications to the copy don't affect the original
The solution
function deepClone(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof Array) {
return obj.map(item => deepClone(item));
}
if (typeof obj === 'object') {
const clonedObj = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
clonedObj[key] = deepClone(obj[key]);
}
}
return clonedObj;
}
return obj;
}Parameters
objobjectObject to deep clone
Put it to work
const original = {
name: "John",
address: {
city: "New York",
country: "USA"
},
hobbies: ["reading", "coding"]
};
const cloned = deepClone(original);
cloned.address.city = "Boston";
console.log(original.address.city); // "New York" (unchanged)