11

Just followed the JavaScript MDN dev docs example to do this:

// Deep Clone
let obj1 = { a:1, b: { c:2 }};
let obj2 = JSON.parse(JSON.strigify(obj1))

Why does it feel wrong to write this code?

Comments
  • 4
    Because you make it a string and then parse that same string.
  • 5
    Use ES6 Object.assign({}, obj1); much cleaner
  • 1
    @Jameslikestea I think let { ...obj2 } = obj1; is the cleanest
  • 1
    Object.assign is a shallow clone isn't it?
  • 1
    @Wavum nope, { ...obj1 } is still not a deep copy :(
  • 0
    @Jameslikestea @juunas
    Object.assign() is not a deep clone.

    Actually there is no good JS solution to deep clone. Even the one I posted loses any methods that you would’ve added to obj1 prototype chain 🧐
  • 1
    @arturgrigio I was under the impression it was if you assign to an empty object and a variable equal the return... never mind
  • 0
    @Jameslikestea easy to test...

    obj1 = {foo:{bar:0}}
    obj2 = Object.assign({}, obj2)
    obj1.foo.bar = 1
    console.log(obj2.foo.bar)

    This should log out: 1 not: 0
  • 0
    @arturgrigio I stand corrected, my apologies for any confusion
  • 1
    Because, like it or not, this is a hack, and although it isn't very legit-looking, it has been proven (at least the last time I researched it) time and time again to be the fastest way to deep clone objects, probably because the JSON parser is so fucking fast due to JSON strings being returned by servers all the fucking time.
Add Comment