Object duplication is an important requirement in JavaScript programming, and it plays an important role in ensuring secure data and avoid referencing. In JavaScript, there are two methods of object copying, "Shallow Copy" and "Deep Copy". However, many new developers in the field often have difficulty putting these methods into practice. So, in this article, we will learn how to clone objects in JavaScript easily and efficiently, including specific examples and important caveats when using these methods.
Before getting into the details of JavaScript object copying methods, let's take a look at what it means to do. copy object.
In JavaScript, objects are used to represent an entity or a set of properties and methods of a specific object. This is especially useful in managing data in web applications or server systems. However, when working with objects in JavaScript, you need to sometimes copy them to ensure data safety and avoid referencing.
For example, when you pass an object from one function to another in JavaScript, if you don't copy the object and pass only its reference, when the object's internal properties or methods change, this affects all objects that access it. This can cause unexpected problems in your application and make your code difficult to manage and maintain.
Therefore, object duplication is an important technique in JavaScript that helps you to solve management related problems data management and ensure the stability of your application. Next, we'll look at specific methods of object copying in JavaScript.
As mentioned at the beginning of the article, there are two main methods of copying objects in JavaScript: "Shallow Copy" and " Deep Copy". However, both of these methods have their own pros and cons, and you need to understand how they work before you use them.
"Shallow Copy" is a method of simply copying an object by creating a new copy of the original object. and point the properties of that copy to the values of the original object. This means that if any properties of the original object change, the properties of the copy will also change.
"Deep Copy" is a method of fully copying an object by creating a complete copy of the object. original image. This includes both the properties and the internal child objects of the parent object. It ensures that if any properties of the original object are changed, the properties of the copy will not be affected.
However, copying objects using the "Deep Copy" method can be expensive in terms of performance, especially is when copying nested or large sized objects. Therefore, it is necessary to consider and choose the most appropriate method depending on the specific situation.
In this article, we'll dive into each method of object duplication and learn how to implement them in JavaScript. We'll also look at specific examples and important caveats when using these methods.
To begin with, we'll learn how to copy objects using the "Shallow Copy" method. To do this we can use some method like Object.assign() or spread operator.
The Object.assign() method is used to copy the properties of one or more objects and assign them to target object. To copy an object using the "Shallow Copy" method using Object.assign(), we can do the following:
const obj1 = { a: 1, b: 2, c: { d: 3 } };
const obj2 = Object.assign({}, obj1);
console.log(obj2); // { a: 1, b: 2, c: { d: 3 } }
obj1.a = 4;
console.log(obj1); // { a: 4, b: 2, c: { d: 3 } }
console.log(obj2); // { a: 1, b: 2, c: { d: 3 } }
In the above example, we used Object.assign() to copy the obj1 object to the empty object { } and assign the result to the obj2 object. Now, if we change the value of a property of object obj1, then the a property of object obj2 is not affected, because object obj2 is just a faint copy of object obj1.< /span>
In addition to Object.assign(), we can also use spread operator (...) to copy objects . Example:
const obj1 = { a: 1, b: 2, c: { d: 3 } };
const obj2 = { ...obj1 };
console.log(obj2); // { a: 1, b: 2, c: { d: 3 } }
obj1.a = 4;
console.log(obj1); // { a: 4, b: 2, c: { d: 3 } }
console.log(obj2); // { a: 1, b: 2, c: { d: 3 } }
Both Object.assign() and spread operator can be used to copy the properties of one or more objects object to the target object. However, if the object has properties that are objects or arrays, they will only be copied by the "Shallow Copy" method. That is, those properties will point to the same memory area.
For a better understanding of the "Shallow Copy" method and the problem with object or array properties, let's consider the following example:
const obj1 = { a: 1, b: 2, c: { d: 3 } };
const obj2 = { ...obj1 };
obj2.c.d = 4;
console.log(obj1); // { a: 1, b: 2, c: { d: 4 } }
console.log(obj2); // { a: 1, b: 2, c: { d: 4 } }
In the above example, we use spread operator (...) to copy obj1 object and assign the result into the obj2 object. Then we change the value of the d property of the c object in the obj2 object. As a result, both obj1 and obj2 objects are affected by this change. This happens because when we copy object obj1 using spread operator, we only copy the reference value of object c into object obj2. Therefore, when we change the value of attribute d in object c of object obj2, the reference value of attribute c in object obj1 is also changed.
To copy object using "Deep Copy" method we can use some library like Lodash or jQuery. For example, to copy object using "Deep Copy" method using Lodash, we can do the following:
const lodash = require('lodash');
const obj1 = { a: 1, b: 2, c: { d: 3 } };
const obj2 = lodash.cloneDeep(obj1);
obj2.c.d = 4;
console.log(obj1); // { a: 1, b: 2, c: { d: 3 } }
console.log(obj2); // { a: 1, b: 2, c: { d: 4 } }
In the above example, we use the Lodash library's lodash.cloneDeep() function to clone the obj1 and assign the result to the obj2 object. Now, when we change the value of property d in object c of object obj2, object obj1 is not affected by this change. This happens because the lodash.cloneDeep() function creates a new copy of the obj1 object, including its properties and values, as well as all nested objects and arrays inside. So, when we change the value of property d in object c of object obj2, object obj1 is not affected by this change.
However, it should be noted that the "Deep Copy" method may affect the performance of the application as it will create a full copy of the original object. Therefore, when copying objects in your application, consider convenience and performance.
Also you can “Deep Copy” in the following ways:
Sử dụng JSON.stringify và JSON.parse:
const obj1 = { a: 1, b: 2, c: { d: 3 } };
const obj2 = JSON.parse(JSON.stringify(obj1));
obj2.c.d = 4;
console.log(obj1); // { a: 1, b: 2, c: { d: 3 } }
console.log(obj2); // { a: 1, b: 2, c: { d: 4 } }
Note that this method only works with simple objects that do not contain functions or related objects DOM. If you want to clone more complex objects, you can use support libraries like Lodash or jQuery.
Or you can write your own deep copy function using recursion.
function deepClone(obj) {
// If object is not object or null, no need to copy
if (obj === null || typeof obj !== "object") {
return obj;
}
// Create a new copy of the object
let clone = {};
// Loop through all the properties of the object
for (let key in obj) {
// Check if the property is a private property of the object
if (obj.hasOwnProperty(key)) {
// If an object, call recursively to create a deep copy
if (typeof obj[key] === "object") {
clone[key] = deepClone(obj[key]);
} else {
// If a primitive value, copy it to a new copy
clone[key] = obj[key];
}
}
}
// Returns a new copy
return clone;
}
const obj1 = { a: 1, b: 2, c: { d: 3 } };
const obj2 = deepClone(obj1);
obj2.c.d = 4;
console.log(obj1); // { a: 1, b: 2, c: { d: 3 } }
console.log(obj2); // { a: 1, b: 2, c: { d: 4 } }
In this article, we learned about two methods of object copying in JavaScript, "Shallow Copy" and "Deep Copy", along with the strengths and weaknesses of each method. When duplicating objects in your application, consider using an appropriate method to ensure the correctness and performance of your application.