DEV Community

Discussion on: Best way to copy an object in JavaScript?

Collapse
 
jvanbruegge profile image
Jan van Brügge • Edited

I would simply use recursion for a deep copy:

function deepCopy(obj) {
 if(typeof obj === 'object') {
  return Object.keys(obj)
   .map(k => ({ [k]: deepCopy(obj[k]) }))
   .reduce((a, c) => Object.assign(a, c), {});
 } else if(Array.isArray(obj)) {
  return obj.map(deepCopy)
 }
 return obj;
}
Enter fullscreen mode Exit fullscreen mode