mark_right
mark_right

Reputation: 33

How does JSON.parse(JSON.stringify(obj)) deep clone an object?

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?

Upvotes: 1

Views: 1819

Answers (1)

James
James

Reputation: 2984

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

Upvotes: 2

Related Questions