Fast clone complex object:
Code
public static deepClone<T>(obj: any) {
if ( obj === null || obj === undefined) {
return obj;
} else if ( Array.isArray(obj)) {
const array: T[] = [];
obj.forEach( item => array.push( this.deepClone<typeof item>(item) ));
return array as T[];
} else {
const c = Object.assign({} as T, obj);
const fields: string[] = Object.getOwnPropertyNames(obj);
fields.forEach( f => {
const field = obj[f];
if ( typeof field === 'object' ) {
c[f] = this.deepClone<typeof field>(field);
}
});
return Object.assign({}, obj);
}
}
Example:
const x = {myProp: 'befor change value', c: {a: 1 , b: 2}, d: [1, 2, 3], func: () => {console.log('befor change function'); }};
const y = Object.assign(x);
const z = Utils.deepClone<any>(x);
console.log(x, y, z);
x.c.a = 12;
x.myProp = 'after change value';
x.func = () => console.log('after change function');
console.log(x, y, z);