我正在尝试克隆嵌套数据对象,以对角度克隆数据执行一些特定操作。但操作完成后,我可以看到对原始datasource.data也进行了更新。
我已经尝试过:
this.reservedDataSource.data = [...this.dataSource.data];
this.reservedDataSource.data = structuredClone(this.dataSource.data);
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;
}
this.reservedDataSource.data = JSON.parse(
JSON.stringify(this.dataSource.data)
);
但我发现所有这些方法都有一个共同点,即在嵌套级别时,原始 dataSource.data 也会更新。在某种程度上,它们都工作得很好。 我需要它来仅更新克隆数据。
cloneDeep
!
var objects = [{ 'a': 1 }, { 'b': 2 }];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
第一个例子除外。其他方法(2 和 4 不会有此警告)请分享一个工作 stackblitz 演示此问题以进行调试!