Deep Copy an Object in Javascript with this easy hack

in #programming6 years ago (edited)

JSON

So I came across this little code snippet that I thought might help some of you Javascript developers out there. I had to use this in a recent project so I thought I would share it here quick.

The problem with using Object.assign is that only the top level properties are actually copied, they may still hold references to other objects. This little hack will make an object that does not share anything with the first object.

let newObject = JSON.parse(JSON.stringify(objectToCopy));

Easy. :)

Keep in mind this way cannot copy method definitions on the object though. For that you might want to try something like the npm package immutability-helper.

Sort:  

Hello! Your post has been resteemed and upvoted by @ilovecoding because we love coding! Keep up good work! Consider upvoting this comment to support the @ilovecoding and increase your future rewards! ^_^ Steem On!

Reply !stop to disable the comment. Thanks!