0

I have the following code:

const list = [{
  items: [
    "2",
    "3",
  ],
}, {
  items: [
    "1",
  ],
}, ];
const selectedList = 0;

const newList = [...list];
newList[selectedList].items = [...list[selectedList].items, "4"];

console.log(list); // X [ { items: [ '2', '3', '4' ] }, { items: [ '1' ] } ] // <-- why does it have 4 inside?
console.log(newList); // ✓ [ { items: [ '2', '3', '4' ] }, { items: [ '1' ] } ]

I expect list to be [ { items: [ '2', '3' ] }, { items: [ '1' ] } ] and newList [ { items: [ '2', '3', '4' ] }, { items: [ '1' ] } ]. Why does list have the '4' as well? I'm spreading the list and not chaning the items of the original list?

Lars Flieger
  • 2,421
  • 1
  • 12
  • 34
  • `[...list]` is a shallow copy, one level deep. Very related: [what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – ASDFGerte Aug 09 '22 at 15:06
  • because spread does shallow copy the inside arrays still have the same reference – cmgchess Aug 09 '22 at 15:07
  • Yes, I know but beside that. The problem was that the object it self was still a reference – Lars Flieger Aug 09 '22 at 15:09
  • 1
    That *is* what is meant with shallow copy. It is not "besides that". That *is* the issue. – trincot Aug 09 '22 at 15:10

1 Answers1

1

Instead of modifying the items property of newList[selectedList], you can create a whole new object. Since it's a new object, it won't have an effect on list[selectedList].

newList[selectedList] = {items: [...list[selectedList].items, "4"]};

const list = [{
  items: [
    "2",
    "3",
  ],
}, {
  items: [
    "1",
  ],
}, ];
const selectedList = 0;

const newList = [...list];
newList[selectedList] = {items: [...list[selectedList].items, "4"]};

console.log(list); // X [ { items: [ '2', '3', '4' ] }, { items: [ '1' ] } ] // <-- why does it have 4 inside?
console.log(newList); // ✓ [ { items: [ '2', '3', '4' ] }, { items: [ '1' ] } ]

    
James
  • 20,957
  • 5
  • 26
  • 41