There's a relatively new (but safe to use, because you don't care about IE anymore) native JS method to deep-copy (also referred to as "cloning") objects: structuredClone()
.
For example:
myObject = {a: 1, b: {c: 2}};
// Uses one of the countless imperfect methods for copying stuff in JS.
myShallowCopy = Object.assign({}, myObject);
// You might expect this not to change myObject. Think again. :-(
myShallowCopy.b.c = 3;
// This will actually copy the object!
myDeepCopy = structuredClone(myObject);
// myObject remains intact! (well, changed by the previous buggy assignment)
myDeepCopy.b.c = 4;
// Uses one of the countless imperfect methods for copying stuff in JS.
myShallowCopy = Object.assign({}, myObject);
// You might expect this not to change myObject. Think again. :-(
myShallowCopy.b.c = 3;
// This will actually copy the object!
myDeepCopy = structuredClone(myObject);
// myObject remains intact! (well, changed by the previous buggy assignment)
myDeepCopy.b.c = 4;
Final thoughts
Perhaps now it's time to get rid of all of these. I mean, this is just the first page of the Google results!: