arraysangulartypescript

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?


Solution

  • 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)));