In this article, we will explore the concept of copying objects in JavaScript.
There are various ways to copy objects in JavaScript which are given below:
- Utilizing the spread (...) syntax
- Utilizing the Object.assign method
- Utilizing the JSON.stringify and JSON.parse methods
We will thoroughly explore each method individually, one at a time.
Utilizing the spread (...) syntax
In JavaScript, we can duplicate objects utilizing the spread (...) operator.
Demonstration:
In this demonstration, we will make use of the spread (...) operator.
Code:
const person = {
firstName: 'Arpit',
lastName: 'Gupta'
};
let p1 = {
...person
};
console.log(person);
console.log(p1);
Output:
It is evident that the object is duplicated through the use of the spread (...) operator. Both objects, "person" and "p1", have been logged to the console. The "person" serves as the original object, while "p1" represents the copy of "person", which accounts for their identical appearance.
Utilizing the Object.assign method
In JavaScript, the Object.assign method allows us to duplicate objects efficiently.
Demonstration:
In this demonstration, we will employ the Object.assign method.
Code:
const person = {
firstName: 'Rahul',
lastName: 'Sen'
};
let p2 = Object.assign({}, person);
console.log(person);
console.log(p2);
Output:
We can observe that the copying of the object is achieved through the Object.assign method. Both objects, "person" and "p2", have been printed. The "person" object serves as the original, while "p2" represents the copied instance of "person".
Utilizing the JSON.stringify and JSON.parse methods
In JavaScript, object duplication can be accomplished using the methods JSON.stringify and JSON.parse.
Demonstration:
In this demonstration, we will make use of the JSON.stringify and JSON.parse functions.
Code:
const person = {
firstName: 'Karishma',
lastName: 'Basu'
};
let p3 = JSON.parse(JSON.stringify(person));
console.log(person);
console.log(p3);
Output:
It is evident that the object has been duplicated through the use of the JSON.stringify and JSON.parse methods. We have displayed both objects: "person" and "p3". Here, "person" refers to the original object, while "p3" represents the copied version of "person".
Both the spread operator (...) and Object.assign generate a shallow copy, while methods that utilize JSON produce a deep copy.
What is a shallow copy?
A shallow copy creates a new object that replicates the original object but retains a distinct reference, while only preserving the reference addresses of the original object's properties. This type of copy only duplicates the properties at the top level of the original object. Consequently, any nested objects are shared between both the original and the cloned object, indicating that the original and cloned objects are interdependent on these nested structures.
What is a deep copy?
A deep copy creates a brand-new object that is an identical replica, meaning it duplicates and retains all elements of the original object, including all its properties and nested objects. The nested objects are distinct and not shared between the original object and the cloned object, signifying that both the original and cloned objects function independently of one another.
Demonstration of a shallow copy:
Let us explore the process of creating a shallow copy through various examples.
Demo:
In the demonstration below, we have utilized the Object.assign method to produce a shallow copy.
Code:
let person = {
firstName: 'Kartik',
lastName: 'Sharma',
address: {
street: 'A-Block Sector 63',
city: 'Noida',
state: 'UP',
country: 'India'
}
};
let copiedPerson = Object.assign({}, person);
copiedPerson.firstName = 'Aryan'; // disconnected
copiedPerson.address.street = 'Vijay Nagar'; // connected
copiedPerson.address.city = 'Ghaziabad'; // connected
console.log(copiedPerson);
Explanation:
An object named "person" has been instantiated, and we have duplicated it using the Object.assign function. Subsequently, we modified the properties firstName, street, and city. Finally, we output the duplicated object to the console.
It is evident that the properties firstName, address-street, and address-city of the duplicated object have been modified.
Next, we will display the original object in the console by employing the code provided below.
console.log(person);
It is evident that the values for address-street and address-city within the original object have been modified. Conversely, the value of firstName remains unchanged since firstName is a primitive value, while the other address attributes are reference values.
Demonstration of a deep copy:
Let us explore how to create a deep copy through the use of illustrations.
Demo 1:
In the demonstration provided, we have generated a shallow copy utilizing the JSON.stringify and JSON.parse methods.
Code:
let product = {
productName: 'Laptop1',
productBrand: 'Dell',
description: {
processor: '13th Gen Intel Core i3',
memory: '8GB',
storage: '512GB',
graphics: 'UHD graphics',
colour: 'Carbon Black'
}
};
let copiedProduct = JSON.parse(JSON.stringify(product));
copiedProduct.productName = 'Laptop2'; // disconnected
copiedProduct.description.processor = '12th Gen Intel Core i5'; // connected
copiedProduct.description.memory = '16GB'; // connected
console.log(copiedProduct);
console.log(product);
Explanation:
We have instantiated an object named "product" and duplicated it using the JSON.parse and JSON.stringify methods. Subsequently, we modified the productName, description-processor, and description-memory properties. Finally, we output the duplicated object to the console.
It can be observed that the attributes productName, description-processor, and description-memory of the duplicated object have been altered.
At this point, we will display the original object in the console by employing the subsequent code.
console.log(product);
It can be observed that the values of the original object remain unaltered since there is no connection between the original object and the duplicated object.
Conclusion:
In this article, we have explored the concept of copying objects in JavaScript. We have examined three distinct methods for duplicating an object in JavaScript. These methods include the spread operator (...), the Object.assign function, and the combination of JSON.stringify and JSON.parse methods.