I have array of two objects:
genericItems: Item[] = []; backupData: Item[] = [];
I am populating my HTML table with genericItems
data. The table is modifiable. There is a reset button to undo all changes done with backUpData
. This array is populated by a service:
getGenericItems(selected: Item) { this.itemService.getGenericItems(selected).subscribe( result => { this.genericItems = result; }); this.backupData = this.genericItems.slice(); }
My idea was that, the user changes will get reflected in first array and second array can be used as backup for reset operation. The issue I am facing here is when the user modifies the table (genericItems[])
the second array backupData
also gets modified.
How is this happening and how to prevent this?
To create a deep copy of an array in TypeScript, install and use the lodash. clonedeep package. The cloneDeep method recursively clones a value and returns the result. The cloneDeep method returns an array of the correct type.
Use the concat function, like so: var arrayA = [1, 2]; var arrayB = [3, 4]; var newArray = arrayA. concat(arrayB); The value of newArray will be [1, 2, 3, 4] ( arrayA and arrayB remain unchanged; concat creates and returns a new array for the result).
Clone an object:
const myClonedObject = Object.assign({}, myObject);
Clone an Array:
const myClonedArray = Object.assign([], myArray);
const myArray= [{ a: 'a', b: 'b' }, { a: 'c', b: 'd' }]; const myClonedArray = []; myArray.forEach(val => myClonedArray.push(Object.assign({}, val)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With