9

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().

Community
  • 1
  • 1
Marin Takanov
  • 1,079
  • 3
  • 19
  • 36

2 Answers2

11

What JSON.parse(JSON.stringify()) won't copy:

  • functions
  • any object that has a special representation, like Date (it will get copied but not as Date)
  • properties with the value undefined

angular.fromJson(angular.toJson()) is basically the same except that angular.toJson() omits properties that are used by Angular internally (those starting with $$).

a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • When do we need to copy only data without function reference, date, undefined values then Which is the best approach? angular.copy() or JSON.parse(JSON.stringify()) – Rohit Shelhalkar May 24 '17 at 09:15
7

I can very specifically answer your question by pointing out they treat undefined differently:

> JSON.parse(JSON.stringify(undefined))
SyntaxError: Unexpected token u

And more generally I would prefer angular.copy:

  • angular.copy says exactly what you want; JSON.parse * JSON.stringify is a hack, from a readability standpoint.
  • angular.copy is almost certainly more performant since it is a higher-level specification of what you are trying to do. If the engineers who wrote it wrote something less performant, they would implement it with the JSON version...

That being said, do they treat more esoteric data, such as functions, the same way? I can't answer this off the top of my head but I would research (or wait for another answer) before deciding.

djechlin
  • 59,258
  • 35
  • 162
  • 290
  • 1
    angular.copy copies the function pointer, +1 for the hack comment. Even if you deliberately want a copy without functions then I would write a function that does just that. don't litter your code base with these hacks. keep them in one place – Liviu T. Apr 21 '15 at 18:38
  • angular.copy will also copy Date instances correctly. – Strille Apr 21 '15 at 18:42
  • Good point by Liviu T, to see the limitations of JSON.parse you should investigate what can be contained within JSON. [w3schools json](http://www.w3schools.com/json/) – Chris Apr 21 '15 at 18:42
  • Maybe they don't implement it with the JSON version because they want it to behave a bit different. So the JSON version could be faster. – Oriol Apr 21 '15 at 18:46