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?
1 Answer
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
JSON.stringifytransforms the entire object into JSON.JSON.parsetakes JSON and constructs a new object.undefined, so if a property hasundefinedas the value, it will be similarly gone, as if it was a function.nulls are good... becausenullis an object.