0

I want to clone an object that has more objects inside of it, without accidentally modifying the first object. To try to explain this more easily, I will try an example with an object that has only one property first

obj1 = {test : "hey"}
obj2 = obj1
obj2.test = "hi"

This will modify the first obj too, which is something that I don't want. After searching a bit I realized I have to do this instead:

obj1 = {test : "hey"}
obj2 = Object.Assign({},obj1)
obj2.test = "hi"

Now obj1 seems to be unmodified. Yay! But here is my problem, I have an object that has nested objects as properties. Imagine that it looks like this:

obj1 = {test : {moretest : "hey"}}
obj2 = Object.Assign({},obj1)
obj2.test.moretest = "hi"

This creates the problem that if I Object.Assign the initial obj1 to obj2, the nested objects will still be passed by reference (so if I change obj2.test.moretest, then obj1.test.moretest will also change, even though I used Object.Assign!)

How can I clone an object by value along with all the nested objects inside of it?

LDinos
  • 103
  • 1
  • 7

0 Answers0