Deep Copy

Deep copy using in built methods

const obj = {
  name: "someone",
  age:30,
  address: {
    location: 'hyd'
  }
}

const outObject = JSON.parse(JSON.stringify(obj));
console.log(outObject) //Prints: {
  name: "someone",
  age:30,
  address: {
    location: 'hyd'
  }
}
outObject.age = 50;
outObject.address = 'Bangalore'
console.log(obj) //Prints: {
  name: "someone",
  age:30,
  address: {
    location: 'hyd'
  }
}
console.log(outObject) //Prints: {
  name: "someone",
  age:50,
  address: {
    location: 'Bangalore'
  }
}

Deep copy without using in built methods

function deepCopy(obj) {

  let value, key;

  if (typeof obj !== "object" || obj === null) {
    return obj;
  }
  
  // Create an array or object to hold the values
  let outObject = Array.isArray(obj) ? [] : {};

  for (key in obj) {
    value = obj[key];
    // Recursively (deep) copy for nested objects, including arrays
    outObject[key] = deepCopy(value);
  }

  return outObject;

}