So I'm always looking for a way to use vanilla JS whenever possible these days, and I discovered that deep copying an object in JavaScript is still weird.
StackOverflow reminded me of the JSON.parse( JSON.stringify( obj ) )
trick, and it looks like Object.assign
still doesn't copy nested objects.
jQuery's $.extend()
works. But that's not vanilla JS any more.
What hacks do you guys use for copying JS objects?
¯\_(ツ)_/¯
Well I suppose it depends on how deep the objects are and whether you have control over the organization of the objects. I believe for simple scenarios, you could do something along the following. Dunno if you qualify ES6 as Vanilla JS, so here's some ES5:
The output to the console:
Alternatively, if you have to handle dynamic objects of unknown dimensions, you could use a recursive function that uses Object.getOwnPropertyNames and the prototypes (someObject.__proto__) of those properties to handle the generation of fresh Objects for the properties of the destination object.
Hope that answers your question!
Edit: Added console output for the above script.