0

I created an object const with a data and I made other const from the first. But my problem is when I change the second object, my first const also is changed.

Have a method to resolve this?

const user1 = {
  name: "samuel"
}

const user2 = user1;

user2.name = "guedes";

console.log(user1); //output: "guedes"
console.log(user2); //output: "guedes"
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 4
    You don't have two objects. It's only one object in total with two labels pointing to it. – VLAZ Mar 09 '22 at 18:11
  • 1
    You probably want to look into using a class. – epascarello Mar 09 '22 at 18:12
  • Welcome to JavaScript :) What you're doing here is creating a reference to user1, and then changing user1.name via the user2 reference. https://stackoverflow.com/questions/29050004/modifying-a-copy-of-a-javascript-object-is-causing-the-original-object-to-change – jsonp Mar 09 '22 at 18:22
  • @jsonp It's not just JS - `a = b` will not *clone* an object in a lot of languages. Same thing happens in Java or C#, for example = you get a second variable but still one object. – VLAZ Mar 10 '22 at 13:59
  • @VLAZ Interesting. I haven't touched C# in like 11 years. I thought it was one of those JavaScript quirks like `typeof NaN === 'number'` – jsonp Mar 10 '22 at 19:05

1 Answers1

-1

Yes, you can use es6

const user1 = {
  name: "samuel"
}

const user2 = {...user1};

user2.name = "guedes";

console.log(user1); //output: "guedes"
console.log(user2); //output: "guedes"
Arezou Saremian
  • 508
  • 3
  • 8
  • Just be careful with nested data, otherwise there will be data loss. OP's scenario (like epascarello said) looks like it requires a User class. But see this thread on deep copying objects: https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – jsonp Mar 09 '22 at 18:19