patternjavascriptCritical
Cloning an array in Javascript/Typescript
Viewed 0 times
arrayjavascriptcloningtypescript
Problem
I have array of two objects:
I am populating my HTML table with
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 (
How is this happening and how to prevent this?
genericItems: Item[] = [];
backupData: Item[] = [];I am populating my HTML table with
genericItemsdata. 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?
Solution
Clone an object:
Clone an Array:
const myClonedObject = Object.assign({}, myObject); Clone an Array:
- Option 1 if you have an array of primitive types:
const myClonedArray = Object.assign([], myArray);- Option 2 - if you have an array of objects:
const myArray= [{ a: 'a', b: 'b' }, { a: 'c', b: 'd' }];
const myClonedArray = [];
myArray.forEach(val => myClonedArray.push(Object.assign({}, val)));Code Snippets
const myArray= [{ a: 'a', b: 'b' }, { a: 'c', b: 'd' }];
const myClonedArray = [];
myArray.forEach(val => myClonedArray.push(Object.assign({}, val)));Context
Stack Overflow Q#44808882, score: 272
Revisions (0)
No revisions yet.