Angular2 - cloning a variable so as not to change the source

I have a component that displays some data on a page from a subscription.

I am trying to clone this variable and make changes to it without affecting the original data used to render the page view.

 import { UtilsService } from '../shared'; import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-review', templateUrl: './review.component.html', styleUrls: ['./review.component.css'] }) export class ReviewComponent implements OnInit { @Input() payload: any = null; // Object of strings that are used for the details langStr: any = { noDepartment: 'No Department Change', noSegment: 'No Segment Change', noMarket: 'No Budget Market Change', noIncentive: 'No Incentive Plan Change', noRole: 'No Role Change', noProductionDate: 'No Production Date Change', noLanguage: 'No Language Change', noShift: 'No Shift Change', noSupervisor: 'No Supervisor Change' }; // Used to scan through the final payload and assign default values if missing optionalFields = ['budgetMarket', 'hierarchy', 'incentivePlan', 'primaryLanguage', 'secondaryLanguage', 'role', 'segment', 'shiftID', 'supervisor']; modifiedData: any; constructor( private utils: UtilsService ) { } ngOnInit() { } submitChanges() { this.modifiedData = this.payload; // Loop over all of the keys in our formData object for (const key in this.modifiedData.formData) { // Find shift by property if the key exists within our defined array if (this.modifiedData.formData.hasOwnProperty(key) && this.utils.isInArray(this.optionalFields, key)) { // If our object data doesnt have a value, set it to -1 if (!this.modifiedData.formData[key].length) { this.modifiedData.formData[key] = '-1'; } } } // Send to database console.log(this.modifiedData) } } 

In this situation above, I am trying to set my signed this.payload data to a new variable called modifiedData . Then I change some data in this assignment.

However, as soon as I call the submitChanges() function, my HTML view receives updates with the changes made to modifiedData , although it did not subscribe to it.

I assume this has something to do with this.modifiedData = this.payload; somehow updating the source data ( payload ).

Is there a way to do this when payload not affected. I just clone this and make a few changes before posting it to my database query.

+5
source share
2 answers

You are not cloning an object. You simply assign a reference to this object to another variable. Both of them point to the same object.

If you want to actually clone your object, you have basically two options:

Firstly, it’s easy, a bit hacked and carefully used, since not everything will be covered:

 this.modifiedData = JSON.parse(JSON.stringify(this.payload)); 

will give you a new object, mostly cloned.

If you want to have more reliable cloning, you need to do it manually by going through your object and creating a new one from scratch (or use a library like lodash, which has methods for doing this).


The update is only for completion: other answers are offered by this.modifiedData Object.assign({}, this.payload) and this.modifiedData = {...this.payload}; which are great for simple rather than nested objects, because both make shallow copy not a deep copy your object.

Since JSON.parse(JSON.stringify(obj) will ignore everything else than objects, arrays, numbers and strings and logical elements, probably the best option is still a manual clone (or using a library that does it like lodash) .

+5
source

Use something like this:

  // Clone the object to retain a copy this.originalProduct = Object.assign({}, value); 

Or in your case:

  this.modifiedData = Object.assign({}, this.payload); 

This copies the values ​​of all properties from this.payload to the new object.

The documentation for this is here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign And includes a discussion of "deep cloning" issues.

Otherwise, this code:

  this.modifiedData = this.payload; 

assigns a link. Thus, any change to the original also changes the “copy”.

+2
source

Source: https://habr.com/ru/post/1270400/


All Articles