3

Please someone tell me there's a better way to copy an object in Javascript...
I can't live with a language where I have to do this

Comments
  • 0
    There is, if you're using jQuery. http://stackoverflow.com/questions/...
  • 0
    There's multiple ways to do it but that's the most efficient way to do a deep copy. Keep in mind that this won't keep functions and won't convert date objects back from string format.
  • 0
    @bluefirex I was actually, for that project, but I'm sure there must be a better way...
  • 0
    @afduarte it depends upon your needs. The most efficient way if you know the structure of the object is to do a manual construction of the cloned object, this won't be a 1 line solution but it's the most efficient. For a 1 line solution, or one where you don't know the object structure you can use extend, or the string parsing. If you're doing a shallow copy, use extend. For a deep copy, stringify/parse is more efficient than extend but has a few limitations.
  • 0
    @port22 Yes, I know that, in that case there were no functions or dates
  • 0
    Stop using Vanilla JS. Start using Angular.

    angular.copy ftw
  • 1
    @PermeableTub For most of the time, I don't, but that was quite a small project for a class and I didn't want to use angular because I'm not familiar enough with it to spin it up as fast as something like Vanilla JS with JQuery
  • 0
    I'm pretty sure looping through the properties, and assigning the to the new object would give you a shallow copy without reference. Would take some tweaking for a deep copy though
  • 0
    lodash has a deep clone function which handles all the tricky corner cases. It's an expensive operation, though I find it hard to imagine it's more expensive than serializing and then parsing. If performance is critical you should probably write your own special purpose clone function which makes use of your knowledge about the structure of the object.
Add Comment