1

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[] = [];
}
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
Felipe Thomé
  • 353
  • 3
  • 12

2 Answers2

1

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.

Jordan Hui
  • 36
  • 5
1

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.