1

I have a Class in Angular 2 and I need two variables with the same json value, but I will need to change one and I need to keep the another one as a backup of the first, like this:

export class Table {
  var1: any;
  var2: any;
}

Then, with a request to API:

ajax_request().then(data => {
  this.var1 = data;
  this.var2 = data;
});

If I make changes in this.var2, this.var1 will be changed too.

To avoid this, I'm making:

this.var1 = data;
this.var2 = JSON.stringify(this.var1);
this.var2 = JSON.parse(this.var2);

But I know It's not performance-friendly. What is the appropriated way to do that?

Daniel Campos
  • 971
  • 4
  • 11
  • 20

2 Answers2

1

This is not related to Angular2 data binding, this is just how JavaScript works.

You need to create a copy of the object to not have a change from one reference affect the other reference to the same object - like you already do in your current workaround.

See also https://stackoverflow.com/a/5344074/217408

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0
this.var1  = Object.assign({}, data);
anshuVersatile
  • 2,030
  • 1
  • 11
  • 18
  • Not functional. – Daniel Campos Nov 07 '16 at 10:48
  • 1
    While this code snippet may solve the question, including an explanation [really helps](//meta.stackexchange.com/q/114762) to improve the quality of your post. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Nov 08 '16 at 13:58