Javascript Object shallow copy

A Javascript shallow copy means that the primitive datatype value of the new variable is disconnected from the original variable and the compositive datatype value of the new variable is connected from the original variable.

You can create shallow copy through the below methods.

1) Object.assign(target_object,source_object);
2) through spread operator

1) Copy through Object.assign() method

Syntax:-


var new_object=Object.assign({},object)

Example:-
Suppose, You have an employee object and copy object through Object.assign() into new object new_employee


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


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

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

}

2) Copy through spread operator

Syntax:-


var new_object={...Object};

Example:-
Suppose, You have an employee object and copy object through spread operator (…) into new object new_employee


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


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

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

}