0

I need to get data from server(or json file) and add them to 'firstVariable' for do some manipulations with it, and 'secondVariable' for default non changed data(the same data from server). But when I change data in 'firstVariable', they are also changing in 'secondVariable'. My question: Why? When I add data to variables I create new array from them. There is an example

dark19
  • 129
  • 6
  • Because you are manipulating the same *reference* type. Add `console.log(data);` and you will see that data is an array of objects, passing it to a new array does not change the fact that the new array will receive pointers to the same instances. – Igor Mar 12 '19 at 20:52
  • Possible duplicate of [Why does changing an Array in JavaScript affect copies of the array?](https://stackoverflow.com/questions/6612385/why-does-changing-an-array-in-javascript-affect-copies-of-the-array) – Igor Mar 12 '19 at 20:53
  • Possible duplicate of [How do you clone an Array of Objects in Javascript?](https://stackoverflow.com/a/23481096/1260204) – Igor Mar 12 '19 at 20:55

1 Answers1

1

The problem you are having is that when you use the spread operator [...data] you are spreading a reference to the objects inside the array.

What you want to do instead is to map the objects into a new object reference, you could do something like

this.json = data.map(x => Object.assign({}, x));

See the following snippet.

let data = [{ id: 123 }];

let a = [...data];
let b = [...data];

a[0].id= 1234;

console.log('Without creating a new object');
data = [{ id: 123 }];
console.log(`A: ${JSON.stringify(a)}`);
console.log(`B: ${JSON.stringify(b)}`);


let c = data.map(x => Object.assign({}, x));
let d = data.map(x => Object.assign({}, x));

c[0].id= 9999;

console.log('Creating a new object');
console.log(`C: ${JSON.stringify(c)}`);
console.log(`D: ${JSON.stringify(d)}`);
Daniel Ormeño
  • 2,743
  • 2
  • 25
  • 30