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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Big (my) mistake to say It's an issue from Angular 2.
Easy to make. It works the way you expect for primitive values like number, string, boolean, but for objects only the reference is copied, not the content.
Yes. After all, I found JSON.parse(JSON.stringify(this.var1)) is the best way to do that.
0
this.var1  = Object.assign({}, data);

2 Comments

Not functional.
While this code snippet may solve the question, including an explanation really helps 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.