Can someone explain the differences between angular.copy() and JSON.parse(JSON.stringify())? Are there any? What you will recommend to use? Is angular.fromJson(angular.toJson()) the same as JSON.parse(JSON.stringify())?
Just to mention, I've read How do I correctly clone a JavaScript object? for JSON.parse(JSON.stringify()) and angular.copy() reference for angular.copy().
parse() is used for parsing data that was received as JSON; it deserializes a JSON string into a JavaScript object. JSON. stringify() on the other hand is used to create a JSON string out of an object or array; it serializes a JavaScript object into a JSON string.
If your deeply-nested object or array only includes certain primitive values (strings, numbers, boolean, and null), then you can use JSON. parse() & JSON. stringify() to deep copy without issues.
The JSON. parse() function is used to convert a string into a JavaScript object while the JSON. stringify() function is used to convert a JavaScript object into a string.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
What JSON.parse(JSON.stringify())
won't copy:
Date
(it will get copied but not as Date
)undefined
angular.fromJson(angular.toJson())
is basically the same except that angular.toJson()
omits properties that are used by Angular internally (those starting with $$
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With