0

Why did the object inside another object value got changed(x.address.city) and why did the name value changed?

why y address field changed to Pune and not the same worked for name?

const x = {
  name: "ABC",
  email: "ac@gmail.com",
  mob: "12345",
  address: {
    city: "Mumbai",
    state: "Maharastra"
  }
};
const y = { ...x }
x.name = "XYZ";
console.log(x.name, y.name);
x.address.city = "Pune";
console.log(x.address.city, y.address.city);

Output:

XYZ ABC 
Pune Pune
Ramanjeet
  • 526
  • 1
  • 5
  • 15

1 Answers1

2

The spread operator in JavaScript does not do a deep copy of the objects, so both objects will keep a reference to the same address object. If you want to make a deep copy, consider using the structuredClone()

Official docs: Structured Clone

Browser Support: Browser Support

Hef
  • 606
  • 6
  • 16
  • 1
    The question is [a dupe](https://www.google.com/search?q=deep+clone+object+javascript+site:stackoverflow.com). – mplungjan Aug 17 '23 at 07:54