Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning an array in Javascript/Typescript

I have array of two objects:

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?

like image 435
Arun Avatar asked Jun 28 '17 17:06

Arun


People also ask

How do you clone an array in TypeScript?

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.

How do I copy an array element to another array in TypeScript?

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).


1 Answers

Clone an object:

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))); 
like image 197
abahet Avatar answered Oct 07 '22 17:10

abahet