0

I tried to clone object and change its value inside an object inside an array of that object. But it affects the original object.

const originalObject = {
  name: "John Doe",
  age: 30,
  arr: [
    {
      num: 1
    }
  ]
};

const copiedObject = Object.assign({}, originalObject);

copiedObject.age = 31;
copiedObject.arr[0].num = 2;

console.log(originalObject); // { name: 'John Doe', age: 30, arr: [ { num: 2 } ] }
console.log(copiedObject); // { name: 'John Doe', age: 31, arr: [ { num: 2 } ] }

spread = {...originalObject};
spread.age = 32;
spread.arr[0].num = 3;

console.log(originalObject); // { name: 'John Doe', age: 30, arr: [ { num: 3 } ] }
console.log(spread); // { name: 'John Doe', age: 32, arr: [ { num: 3 } ] }

I tried both spread operator and Object.assign() but it doesn't work. So any help is appreciated. Thanks in advance.

ThavinV
  • 3
  • 3
  • 1
    Also check [Warning for Deep Clone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#warning_for_deep_clone) – Justinas Aug 30 '23 at 10:55

1 Answers1

1

Your current method of Object.assign() is only creates a shallow copy, however your object is nested. You should avoid this approach in a multilevel object.

Instead, use const clone = structuredClone(originalObject) this creates a deep cloned object in a new memory space that won't mutate your original object.

Alternatively, if you only work with primitive types, you can use const clone = JSON.parse(JSON.stringify(originalObject)) which does the same, however I wouldn't use it if your object contains a date object for instance.

Benji
  • 280
  • 3
  • 15