Object coping issue in angular

--

when we want to get a copy of an exciting object and make some changes and send it through API but the changes have applied to the exciting object it because passing by reference is used to copy the object,so what is Passing by reference and Passing by value means

  • When a parameter is passed by reference, the caller and the callee use the same variable for the parameter. If the callee modifies the parameter variable, the effect is visible to the caller’s variable.
  • When a parameter is passed by value, the caller and callee have two independent variables with the same value. If the callee modifies the parameter variable, the effect is not visible to the caller.

The clean way of deep copying objects having nested objects inside is by using lodash’s cloneDeep method.

For Angular, you can do it like this:

Install lodash with yarn add lodash or npm install lodash.

In your component, import cloneDeep and use it:

import * as cloneDeep from 'lodash/cloneDeep';
clonedObject = cloneDeep(originalObject);

after that you can use Object.assign(clonedObject, newObjectdata)

clonedObject = cloneDeep(originalObject);

--

--