0

"I am looking for a reliable approach to implement a deep clone function in JavaScript that can create a complete copy of an object, including all nested properties and arrays. While I've tried using JSON.parse(JSON.stringify(obj)) for shallow cloning, it doesn't work for nested objects since it only creates a shallow copy. I want to find a robust solution that can handle cloning objects with complex nesting.

I've attempted to write a recursive function, but it's not functioning as intended. Here is my current implementation:

function deepClone(obj) {
  if (typeof obj !== 'object' || obj === null) {
    return obj;
  }
  
  let clone = Array.isArray(obj) ? [] : {};
  
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key]);
    }
  }
  
  return clone;
}

// Usage example:
let originalObj = {
  name: 'John',
  age: 30,
  address: {
    street: '123 Main St',
    city: 'New York',
    state: 'NY'
  },
  hobbies: ['reading', 'cooking', 'swimming']
};

let clonedObj = deepClone(originalObj);

However, any modifications made to clonedObj or its nested properties also reflect in the originalObj. Could someone suggest an effective solution to implement a deep clone function that properly handles nested objects in JavaScript? Your assistance would be greatly appreciated. Thank you!"

Haitham6373
  • 1,139
  • 8
  • 10
  • 4
    You're wrong, `JSON.parse(JSON.stringify(obj))` creates a deep copy. How could `JSON.parse()` possibly keep references to nested objects intact? – Barmar Jun 05 '23 at 14:50
  • There is a million of answers regarding this question.. [here](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript?rq=1) – hastrb Jun 05 '23 at 14:53
  • 2
    And your function also seems to work for me. You must be making mistakes when testing whether changing one affects the other. – Barmar Jun 05 '23 at 14:55
  • AFAICT this works fine; changes to the original or the clone don't appear to be reflected in the other. – Dave Newton Jun 05 '23 at 14:59
  • This question makes no sense since what you want is `JSON.parse(JSON.stringify(obj))` but you say it's not doing what you want. Are you trying to clone an object that can't be represented by JSON? Like do your objects contain things like functions? – slebetman Jun 05 '23 at 15:25

1 Answers1

0

Use structuredClone function StructuredClone is new feature by which u can deep copy the objects arrays etc Link https://developer.mozilla.org/en-US/docs/Web/API/structuredClone Examples

const obj = {name: "Mark"}
let deepclone = structuredClone(obj)
deepclone.name = "JOHN"
console.log(deepclone.name) // JOHN
console.log(obj.name) // Mark
COLONEL FF
  • 34
  • 4