Avoid Angular/TypeScript variable binding

329 Views Asked by At

I need to create a clone of my object, without creating it's reference. When I try to copy EquipmentClass, witch is my main object to it's clone, and if I change some property of EquipmentClass it will change my EquipmentClassCloneEdit also. And I don't want that to happen.

I tried to assign the value like this:

this.equipmentClassCloneEdit = Object.assign({}, this.equipmentClass);

this is my model:

export class EquipmentClass {
    equipmentClassId: number;
    name: string;
    description: string;
    isDeleted: boolean;
    propertyValuesList: EquipmentClassPropertyValue[] = [];
}
2

There are 2 best solutions below

0
On BEST ANSWER

Try this.equipmentClassCloneEdit = JSON.parse(JSON.stringify(this.equipmentClass))

Object.assign() creates a shallow copy, so it wouldn't work on non-primitives like your propertyValuesList array.

0
On

You can use lodash's cloneDeep method to do a deep clone. https://lodash.com/docs/#cloneDeep

  1. install 'lodash' package
  2. import cloneDeep from 'lodash/cloneDeep';
  3. just call it: this.equipmentClassCloneEdit = cloneDeep(this.equipmentClass);

Using this kind of cloning functions is better from stringify and then parse solution as it also keeps members which JSON ingores when stringifying, like, Functions, Symbols, BigInts etc.