-1

Consider the following code,

let a =[{b:{c:100}}]
let c = [...a]
c[0].b = {l:200}
console.log( a )

Output is:

Array [Object { b: Object { l: 200 } }]

Given c[0] is a new object and c[0].b is a reference. Changing the reference of b should not change the original object. Is there any explanation for this?

muhammad800804
  • 105
  • 1
  • 8

2 Answers2

0

The spread operator method only performs a deep copy of the array itself, and not the objects inside it. The objects in c are only by reference, and they point to the objects in a in reality.

The most reliable way remains using JSON.stringify and then JSON.parse. The catch is that there will be some data loss if you have special types in the array.

function clone(arr) {
  return JSON.parse(JSON.stringify(arr));
}

let a =[{b:{c:100}}]
let c = clone(a);
c[0].b = {l:200}
console.log( a )
Terry
  • 63,248
  • 15
  • 96
  • 118
0

even if you use the spread operator the changes are done on the same reference. So in your json sample there is no date objects, so you can use this approach. if there is date object this approach won't work.

let c = JSON.parse(JSON.stringify(a));
c[0].b = {l:200}
console.log( a )
Sayooj V R
  • 2,255
  • 2
  • 11
  • 23