1

This is my object

const person = {
  name: "Vikram",
  age: 21,
  place: {
    country: "India",
    state: "Karnataka",
  },
  marks: [1, 2, 3, 4],
  parents: {
    father: "Ramesh",
    mother: "Suma",
  },
};
function cloneDeep(obj){} 
 

that should create a deep copy of the provided object using recursion and methods like Object.create etc. Please help me to deep copy this object using recursion.

  • Of course: it’s called monkey-patching and is done by extending `Object.prototype`. See [this answer](/a/46491279/4642212) which provides a template. Whatever you do, don’t extend the prototype without checking if it exists first. This is how compatibility bugs arise that are impossible to fix. – Sebastian Simon Sep 22 '21 at 05:56
  • 1
    Obviously, I would still **strongly advise against** this practice. – Sebastian Simon Sep 22 '21 at 06:02
  • some people use JSON.stringify and JSON.parse for this. – The Fool Sep 22 '21 at 06:23
  • I would just stringify it and parse into back into a new variable. Less complicated. – Andy Sep 22 '21 at 06:23
  • Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript). There are many ways to deep clone and you could pick one from this answer. – Lakshya Thakur Sep 22 '21 at 06:28

1 Answers1

0

Yes, you can alter the Object class prototype:

if (!Object.prototype.hasOwnProperty.call(Object.prototype, "deepClone")) {
  Object.prototype.deepClone = () => {
    console.log('clone!')
  };
}

const obj1 = { x: 1 };

obj1.deepClone();
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
MorKadosh
  • 5,846
  • 3
  • 25
  • 37