How to Deep Copy a JavaScript Object?

Estimated read time 1 min read

To perform a deep copy of a JavaScript object, which means creating a new object with the same properties and values as the original object but with different references, you can use a combination of the Object.assign method and recursion.

Here’s an example implementation:

function deepCopy(obj) {
  if (typeof obj !== "object") return obj;
  let newObj = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    newObj[key] = deepCopy(obj[key]);
  }
  return newObj;
}

You can use this function like this:

const original = { a: 1, b: { c: 2, d: [3, 4, 5] } };
const copy = deepCopy(original);
console.log(copy); // { a: 1, b: { c: 2, d: [3, 4, 5] } }

This implementation will handle complex data types and nested objects. Note that this method does not handle circular references, so it may cause an infinite loop in such cases.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply