Shallow Copy
A shallow copy is a copy of an object whose references are the same as the original object. This means that if you change the value of a property in the shallow copy, it will also change the value of the property in the original object.
const user = {
name: "Kingsley",
age: 28,
job: "Web Developer"
}
const clone = user
Methods -
Spread Operator(…): any object with a nested object will not be deep copied.
const originalObject = { name: "Alice", age: 25 };
const deepCopy = {...originalObject};
deepCopy.name = "ravi"
console.log("originalObject", originalObject.name) // Alice
Object.assign(): the Object.assign() method should be used to deep copy objects that have no nested objects.
const originalObject = { name: "Alice", age: 25 };
const shallowCopy = Object.assign({}, originalObject);
Deep Copy
A deep copy is a copy of an object whose references are not the same as the original object. This means that if you change the value of a property in the deep copy, it will not change the value of the property in the original object.
Methods -
there different ways to create deep copy of an object.
a)JSON.parse and JSON.stringify: useful for nested object also.
const originalObject = { name: "Alice", age: 25 };
const deepCopy = JSON.parse(JSON.stringify(originalObject));
b)structuredClone:
const myDeepCopy = structuredClone(myOriginal);
Recursion:
function deepCopy(obj) {
if (typeof obj !== 'object' || obj === null) {
return obj;
}
const newObj = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
newObj[key] = deepCopy(obj[key]);
}
}
return newObj;
}
const originalObject = { name: "Alice", nested: { age: 25 } };
const deepCopy = deepCopy(originalObject);
Top comments (0)