-1

I have such object:

const obj = {age: 20}

But value of age can be changed , for example, to 30; Then I need to compare previous object's values and new object's values. So how I can save first object before it will change it's structure.

const obj = {age: 20} //object what I have at the beggining
const newObj = obj; // {age: 30}
JSON.stringify(obj) === JSON.stringify(newObj) // false

1 Answers1

1

you should not mutate an obj, instead you can create a new copy using ... syntax:

const obj = {age: 20};
const newObj = {...obj}; 

Then do what you want to do with newObj

Shivam Jha
  • 3,160
  • 3
  • 22
  • 36
  • It works for me, only when I change object 1 time, but when i change 2 or more times it saves what it was before. For example, firstly age = 20, then i changed to 30, copy has value age which is = 20, but when i change 30 to 40, copy has value age which is = 30. Can I copy one time and save it? – werwe werwer May 06 '21 at 14:18
  • you need to make a copy every time you edit it. – Shivam Jha May 06 '21 at 14:24