Remove variable value link

Viewed 28
public oldClient: Client = new Client(); 
public client: Client = new Client();
private clientId: string = "xxx";

this.userService.getClient(this.clientId).subscribe((data: Client) => {
    this.client = data;
    this.oldClient = data;
    this.client.name = "test";

    console.log(this.client.name) // Output : "test"
    console.log(this.oldClient.name) // Output : "test"
});

Why when im changing a property from my variable "client" this will impact "oldCLient" and how can I prevent this ? Thanks.

2 Answers

Use the ...(spread syntax) to create the new object.

this.client = {...data} 

If you just assign one object to another, you'll just have two variables pointing to the same object in memory, ie, editing one will change the original object.

You can create a clone of the data object to lose reference using

var a = Object.assign({}, b);

In your case

this.client = Object.assign({}, data);
this.oldClient = Object.assign({}, data);
Related