4

Came across this snippet

var someDataJSON = jQuery.parseJSON(JSON.stringify(someData));

According to MDN the inner "method converts a JavaScript value to a JSON string"; then the outer method "Takes a well-formed JSON string and returns the resulting JavaScript value" per jQuery

If you start with a JS value & end up with a JS value, is this a pointless operation?

Merrick
  • 237
  • 3
  • 11
  • 2
    There's no point unless there's some point in the example you're looking at. Where did you come across that snippet? Is this something that Proconsul Claudius Marcus put you up to? – Pointy Jul 09 '15 at 04:28
  • My personal favorite solution for object cloning by value is the [`history.replaceState` structured clone hack](http://stackoverflow.com/a/10916838/1541563). – Patrick Roberts Jul 09 '15 at 04:34
  • @Pointy the code isn't open source; but now that I know it's a object copy hack, things make more sense ;-) – Merrick Jul 09 '15 at 14:50

2 Answers2

4

Usually that is a trick used to get a by-value copy of an object in javascript. (Since all objects are passed by reference). You can find a more in-depth answer on how to accomplish this, if you're curious, in this stackoverflow post

Community
  • 1
  • 1
dnapierata
  • 1,153
  • 1
  • 16
  • 28
  • 2
    This is true but it should be noted that unless one knows that the objects involved are pretty small, it's a sub-optimal way to make a copy. – Pointy Jul 09 '15 at 04:32
  • 1
    Thanks for linking that post; I didn't actually know copying JS objects could be that complex?! – Merrick Jul 09 '15 at 14:59
2

If someDataJSON is a flat JSON object, this way you get a copy of that object. Since, there is no direct method to copy a javascript object "by value" [and not "by reference"], this trick can be used.

var copyJSONObj = JSON.parse(JSON.stringify(JSONObj))

So, there is some point after all.

Suman Barick
  • 3,311
  • 2
  • 19
  • 31