DEV Community

Discussion on: Best way to copy an object in JavaScript?

Collapse
 
hosembafer profile image
Rafael Hovhannisyan • Edited

In plain javascript, there is only one option.

JSON.parse( JSON.stringify( obj ) );
Enter fullscreen mode Exit fullscreen mode

I don't know how and why, but in some cases Object.assign is working, but it's not recommended for use without deep understanding of it.

Collapse
 
isaacdlyman profile image
Isaac Lyman

This is great for simple object literals. But, if someone out there tries it and it doesn't work, allow me to offer some reasons why.

  • JSON.parse will fail for any object that recurses on itself. Try this in your console: var a = {}; a.a = a; JSON.stringify(a);. This is uncommon in app-level code, but happens a lot in DOM parsing libraries and frameworks.
  • This method doesn't allow you to make "shallow copies" (copies of the immediate properties of the object, without going any deeper). jQuery and Lodash, on the other hand, have options that allow you to do this.
  • Objects that have a toJSON() method will not truly be copied as-is. The toJSON() method will be invoked and its response will be assumed to be correct JSON, whether or not it corresponds to the actual properties of the object.
  • Methods will not be copied.
  • Dates will be parsed as Strings, not as Dates.

To cover your own butt, you're better off doing as others have suggested and using jQuery or Lodash. In modern ES6 code, you don't have to worry about code bloat, since you can just import the method you want to use from either toolkit and the rest of the library won't get included in your browser bundle.