尝试以角度克隆mat-table嵌套datasource.data

问题描述 投票:0回答:1

我正在尝试克隆嵌套数据对象,以对角度克隆数据执行一些特定操作。但操作完成后,我可以看到对原始datasource.data也进行了更新。

我已经尝试过:

  1. 价差运算符:
this.reservedDataSource.data = [...this.dataSource.data];
  1. 结构化克隆:
this.reservedDataSource.data = structuredClone(this.dataSource.data);
  1. deepClone 的独立功能(在此处找到):
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. 和 JSON.pares & JSON.stringify:(它也字符串化所有对象)
          this.reservedDataSource.data = JSON.parse(
            JSON.stringify(this.dataSource.data)
          );

但我发现所有这些方法都有一个共同点,即在嵌套级别时,原始 dataSource.data 也会更新。在某种程度上,它们都工作得很好。 我需要它来仅更新克隆数据。

angular tree datasource clone angular-material-table
1个回答
0
投票

尝试 lodash

cloneDeep

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

第一个例子除外。其他方法(2 和 4 不会有此警告)请分享一个工作 stackblitz 演示此问题以进行调试!

© www.soinside.com 2019 - 2024. All rights reserved.