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:
- the spread operator:
this.reservedDataSource.data = [...this.dataSource.data];
- structuredClone:
this.reservedDataSource.data = structuredClone(this.dataSource.data);
- 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;
}
- 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.
Try lodash
cloneDeepinstead!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!