Laczkó Örs
Laczkó Örs

Reputation: 1118

Creating an Array clone with spread operator, but it still has reference to original array

So I have these few lines of code:

  console.log(...cells);

  let testCells = [...cells];
  testCells[index].shape = selectedShape;
  testCells[index].player = player;

  console.log(...cells);

The interesting thing is that it is console.log()ing back the following.

enter image description here

I don't quite get it, why does cells change? There is no other part of the code that could interfere with cells. Any tips?

Full code available here.

Upvotes: 2

Views: 224

Answers (1)

async await
async await

Reputation: 2395

It looks like even though you're spreading all the objects into the new array, it is still a reference to the old objects. You can break the reference by using JSON.stringify and JSON.parse to avoid any old unintended relationships.

  const cells = [
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
    {shape: 0, player: 0},
  ];
  
  console.log(...cells);
  
  const breakRef = obj => JSON.parse(JSON.stringify(obj));

  let testCells = breakRef(cells);
  testCells[0].shape = 1;
  testCells[0].player = 0;

  console.log(...cells);

Upvotes: 1

Related Questions