Search code examples
javascriptreferencejavascript-objects

Prevent object created by reference to change when the original one is changed


Probably this thing was talked before but I haven't find a solution to solve my problem yet.

So, my issue is this:

I'm saving into a variable the value of an object.

const aux = this.myObj;

the Object (this.myObj) is changed by some operations after that but I want to save its initial value and be able to re-assing it to it.

Something like:

this.myObj = aux

but as expected, the aux is also modified when the original one is.

Is there a solution to this?


Solution

  • You need to clone the object and save it's data to the other variable.

    var clone = Object.assign({}, obj);
    

    In case of nested object, Deep cloning can be achieved using various methods. One of that for a simple structured object with nested key-value pairs.

    var clone = JSON.parse(JSON.stringify(obj));
    

    or use library like underscore and lodash.