What is the meaning of Deep Copy:
Objects or arrays that contain nested objects or arrays require a deep copy.
In other words, you can say nested objects or arrays require a deep copy.
Why do we need a deep copy?
In the direct copy, the nested objects or arrays will be copied by reference, so the changes made to the nested object or array will change the data in the original object or array.
Examples:
var Person = {
name: {
firstName: 'A',
lastName: 'B'
},
DOB: {
day: '01',
month: '08',
year: '2000'
}
}
// Direct copy by assignment operator(=)
var Person1 = Person;
console.log(Person1 === Person) // true;
Person1.name.firstName = 'C'; // It will change the data in the original nested object
console.log(Person1.name.firstName === Person.name.firstName) // true;
// Deep copy by the JSON.stringify and JSON.parse
var Person2 = JSON.parse(JSON.stringify(Person));
console.log(Person2 === Person) // false;
Person2.name.firstName = 'D';
console.log(Person2.name.firstName === Person.name.firstName) // false;
How JSON.parse(JSON.stringify(Object)) works:
JSON.stringify(Object):
It converts a javascript object into a string.
var object = { name: "John", age: 30, city: "New York" };
var stringObject = JSON.stringify(object);
console.log((typeof stringObject)); // string
JSON.parse(jsonString):
It converts a JSON format string into a javascript object.
var object = '{"name":"John","age":30,"city":"New York"}';
console.log((typeof object)); // string
var jsonObject = JSON.parse(object);
console.log((typeof jsonObject)); // object
Conclusion:
This approach only works when the object or array contains the JSON-serializable content i.e no functions, no Number.POSITIVE_INFINITY, etc.
We can make a deep copy of an array too with the same method.
Example:
var arr1 = [['A'], ['B'], ['C'], ['D']];
var arr2 = arr1; // direct copy.
console.log(arr2 === arr1); // true
console.log(arr2[0] === arr1[0]); // true
var arr1 = [['A'], ['B'], ['C'], ['D']];
var arr2 = JSON.parse(JSON.stringify(arr1)); // deep copy.
console.log(arr2 === arr1); // false
console.log(arr2[0] === arr1[0]); // false