1

I want to make a deep copy of a object, say I have a object:

const oriObj = {
  id: 1,
  version: 1,
  person: 'jack'
};

so after a click event, oriObj is set to be a empty array [], but I still want to get the original value in the oriObj for example the id and version. I was trying to make a deep copy, so the no matter how oriObj is changing, once I am getting the value of oriObj in the beginning, I deep copy it and store in so it won't become empty array. I have tried several method, but it won't work, I am still getting empty array after the click event.

Jonas Lu
  • 181
  • 1
  • 12
  • What have you tried so far? It could be you just made a simple mistake. If you post your attempts we might be able to diagnose what you're doing wrong. – Daniel Lane Aug 12 '20 at 15:14
  • Does this answer your question? [What is the most efficient way to deep clone an object in JavaScript?](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript) – Graham Aug 12 '20 at 15:14
  • if you felt like the "click event" was relevant enough to mention, then you probably should have shown that code. you could have easily found several ways of cloning an object on google, but if those didn't work for you then you need to show enough code so we can figure out why. – I wrestled a bear once. Aug 12 '20 at 15:19

1 Answers1

1

If it's a simple object with no methods, one quick way is to serialize the object and then parse it again.

const oriObj = {
  id: 1,
  version: 1,
  person: 'jack'
};

const copy = JSON.parse(JSON.stringify(oriObj));

oriObj.id = "changed this";

console.log(oriObj, copy);
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116