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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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.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.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.