0

I'm currently working on some homework and encounter some weird behavior ( to me ) about changing properties value in a object . Show in below code :

    // let say I have a object 
    const a = {
      name:"origin",
      arr:["origin"],
    }

    // then I create another object and fill that object with props of "a"
    
    const b = {...a}
    
    // then doing some mutate with props of "b"
    
    b.name = "mutated";
    b.arr.push("mutated");
    
    
    // but it also change "arr" props of "a" (name is not change)
    
    console.log(a.name); // log "origin"
    console.log(a.arr);// log ["origin", "mutated"]

I don't understand why it also changed the props of a . Can anyone explain it for me ? Am I using the wrong technology here (...) ? Thanks a lot

Dusttt
  • 19
  • 6

1 Answers1

0

Object rest { ...someObj } only creates a shallow copy of the someObj. The new object will be new, but if the old object property values happened to be objects themselves - like arrays or objects - then mutating those in either the new or the old object will be seen in both.

enter image description here

If you want a change to the arr not to change the original, make a copy explicitly, eg

// let say I have a object 
const a = {
  name:"origin",
  arr:["origin"],
}

// then I create another object and fill that object with props of "a"

const b = {...a, arr: a.arr.slice() }
b.name = "mutated";
b.arr.push("mutated");

console.log(a.name); // log "origin"
console.log(a.arr);// log ["origin"]
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320