1

Let's say we got this:

this.myObject = {"id":1};

and we want to store the state of my object as my object original as the following:

this.myObjectORG = this.myObject;

then you go on your business and change props on your object like this

this.myObject.id = 2;

and to your surprise down the road, you realize that

console.log (this.myObjectORG.id) // also reports 2

Well, that's just how JS works & I'm not questioning that.

Is there a way to preserve the state of the myObject so I can do comparisons whether its properties changed since its original state?

At some point I'd like to be able to do something like this

if ( this.myObjectORG.id !== this.myObject.id ) {
   // but this condition is never true 
}
Average Joe
  • 4,521
  • 9
  • 53
  • 81
  • 1
    What you are basically asking for is, how to create a copy of an Object, so you can handle the Object and the copy indepedently. A simple search in a searchengine for "how to copy js Object" will lead you to n answer: https://stackoverflow.com/questions/728360/how-do-i-correctly-clone-a-javascript-object#728694 If you understand, what your problem really is, it is much easier, to find an answer. Hope it helps you to tackle future questions, that arise – Syntac Dec 12 '17 at 14:30
  • good point. agreed. – Average Joe Dec 12 '17 at 14:39

1 Answers1

3

Does this help:-

An Object.assign method is part of the ECMAScript 2015 (ES6) standard and does exactly what you need.

var this.myObjectORG = Object.assign({}, this.myObject);

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object.

p.wright
  • 131
  • 1
  • 9