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?

7
  • 1
    JSON.stringify transforms the entire object into JSON. JSON.parse takes JSON and constructs a new object. Commented Oct 17, 2019 at 8:23
  • …and JSON is just a string. There's no way a string can hold any sort of reference to an object… Commented Oct 17, 2019 at 8: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. Commented Oct 17, 2019 at 8: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. Commented Oct 17, 2019 at 8:28
  • But nulls are good... because null is an object. Commented Oct 17, 2019 at 8:31

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.