Javascript Object Deep copy

Javascript Object deep copying means that the value of the new variable is disconnected from the original variable.
You can create the deep copying through JSON.parse method with JSON.stringify

Syntax:-


let new_object_name = JSON.parse(JSON.stringify(object_name));

Example:- Suppose you have employee object and copy object through JSON.parse() method with JSON.stringify into new_employee object then you change the firstName, city and state in new_employee object then it will not connected to old employee object.


let employee = {
    firstName: 'John',
    lastName: 'Taylor',
    address: {
        city: 'Mumbai',
        state: 'Maharashtra',
        country: 'India'
    }
};


let new_employee = JSON.parse(JSON.stringify(employee));
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // disconnected
new_employee.address.state = 'Delhi'; // disconnected
console.log(new_employee);
console.log(employee);
Output:-
newEmployee:- {
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}

oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “Mumbai”, state: “Maharashtra”, country: “India”}

}