1

I'm searching articles about deep clone javascript obj on the web, but most of them said that using JSON.parse(JSON.stringify(obj)) can do it, however, do not explain why this method will deep clone obj?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
mark_right
  • 33
  • 4
  • 1
    `JSON.stringify` transforms the entire object into JSON. `JSON.parse` takes JSON and constructs a new object. – VLAZ Oct 17 '19 at 08:23
  • …and JSON is just a string. There's no way a string can hold any sort of reference to an object… – deceze Oct 17 '19 at 08:23
  • 1
    In addition to what @VLAZ has said, it doesn't actually clone everything. It won't copy functions or custom type information like JS classes. You're limited to some primitives like numbers, booleans, strings, object and arrays. – Soc Oct 17 '19 at 08:26
  • @Soc also, it would strip away all `undefined`, so if a property has `undefined` as the value, it will be similarly gone, as if it was a function. – VLAZ Oct 17 '19 at 08:28
  • But `null`s are good... because `null` is an object. – Soc Oct 17 '19 at 08:31
  • @VLAZ Thank you for your answer. I got some understand. – mark_right Oct 17 '19 at 08:38
  • @Soc no, actually [the `typeof` output is a bug](https://stackoverflow.com/questions/18808226/why-is-typeof-null-object) in the first version of JS but was kept for backwards compatibility. The reason `null` works is because [the JSON standard defines it as a valid value](http://json.org/). – VLAZ Oct 17 '19 at 08:46

1 Answers1

2

JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string, eg:

var my_object = { key_1: "some text", key_2: true, key_3: 5, key_6: [{}] };

var object_as_string = JSON.stringify(my_object);  
// "{"key_1":"some text","key_2":true,"key_3":5,"key_6":[{}]}"

typeof(object_as_string);  
// "string"  

So here, all the objects and array has lost it's reference.

And when we do JSON.parse turns a string of JSON text into a JavaScript object, eg:

var object_as_string_as_object = JSON.parse(object_as_string);  
// {key_1: "some text", key_2: true, key_3: 5, key_6: Array(1)}

typeof(object_as_string_as_object);  
// "object" 

Now the resulting objects got the new storage reference. Let's test it by checking the reference of array inside the parent object an example.

my_object.key_6 === my_object.key_6
// true  

But, if we try

 my_object.key_6 === object_as_string_as_object.key_6
// false
James
  • 2,874
  • 4
  • 30
  • 55