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[] = [];
}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.