0

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.

3
  • 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. Commented Aug 12, 2020 at 15:14
  • 2
    Does this answer your question? What is the most efficient way to deep clone an object in JavaScript? Commented Aug 12, 2020 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. Commented Aug 12, 2020 at 15:19

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

2 Comments

it does not work with functions.
@TijuJohn - Read the answer before you comment. I explicitly said that in the first sentence.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.