Trying to clone mat-table nested datasource.data in angular

43 Views Asked by At

I'm trying to clone a nested data object to perform some specific operations on cloned data in angular. But after the operations are completed, I can see the update also made to original datasource.data.

I have tried:

  1. the spread operator:
this.reservedDataSource.data = [...this.dataSource.data];
  1. structuredClone:
this.reservedDataSource.data = structuredClone(this.dataSource.data);
  1. a separate functionality of deepClone (found here):
deepClone(obj: any): any {
    if (obj === null || typeof obj !== 'object') {
      return obj;
    }
    if (Array.isArray(obj)) {
      return obj.map(this.deepClone.bind(this));
    }
    if (obj instanceof Date) {
      return new Date(obj.getTime());
    }
    const clonedObj: any = {};
    for (let key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        clonedObj[key] = this.deepClone(obj[key]);
      }
    }
    return clonedObj;
  }
  1. and JSON.pares & JSON.stringify:(It also stringify all objects)
          this.reservedDataSource.data = JSON.parse(
            JSON.stringify(this.dataSource.data)
          );

But I've found common thing in all those methods, when in nested levels, the original dataSource.data is also getting updated. On one level they all work fine. I need it to update only the clone data.

1

There are 1 best solutions below

2
Naren Murali On

Try lodash cloneDeep instead!

var objects = [{ 'a': 1 }, { 'b': 2 }];
 
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);

Also except the 1st example. The other methods (2 and 4 will not have this caveat) please share a working stackblitz demonstrating this problem for debugging!