deep copy objects
Sun Jun 19 2022 04:40:24 GMT+0000 (UTC)
Saved by
@joeclaap
#javascript
#object
#deep
#copy
#clone
#recursion
function deepCopy(obj){
let toString = Object.prototype.toString;
if(typeof obj !== 'object') return obj;
if(obj === null) return null;
if(Array.isArray(obj)) return obj.map(deepCopy);
let newObj = {};
for(let key in obj){
if(toString.call(obj[key])==='[object Date]'){
newObj[key] = new Date(obj[key])
} else if(toString.call(obj[key])==='[object RegExp]'){
newObj[key] = new RegExp(obj[key])
}else{
newObj[key] = deepCopy(obj[key]);
}
}
return newObj;
}
content_copyCOPY
Comments