Core points
...
) and the Object.assign()
methods. The expand operator is more modern and concise, while the Object.assign()
is more compatible and suitable for older environments. Object.assign()
both perform shallow copies when merging objects, meaning that the nested object is still a reference to the original object. Modifying nested objects in merged objects may affect the original object, resulting in potential unexpected side effects. deepMergeObjects
is provided in the article, which creates a depth copy of the object before merging it using the JSON.parse(JSON.stringify())
technique. Developers often need to merge or copy objects to complete tasks such as composing data or creating new instances. Techniques such as the expand operator (...
) (used to merge properties of multiple objects) and the Object.assign()
method (used to copy properties of one object to another) are important tools for completing these tasks. However, understanding when and how to use them is essential to efficiently manipulate objects. In this article, I will introduce some practical applications of these methods, their advantages and disadvantages, and the concept of deeply copying and then merging nested objects.
Catalog
...
)Object.assign()
Method Object Merge Method
...
)Expand operator (...
) is a common method for merging objects in JavaScript. Its form is { ...object1, ...object2 }
. When there are attributes with the same key in the source object, the expand operator overwrites the value in the target object with the latest source object's numeric value.
const defaults = { color: 'red', size: 'medium' }; const userSettings = { color: 'blue' }; const combinedSettings = { ...defaults, ...userSettings }; console.log(combinedSettings); // 输出:{ color: 'blue', size: 'medium' }
Object.assign()
Method Object.assign()
is another method used in JavaScript to merge objects. Its syntax is Object.assign(target, source1, source2, ...)
, where the source object is merged into the target object. When there are attributes with the same key in the source object, Object.assign()
will overwrite the values in the target object with the latest source object's numerical value.
const defaults = { color: 'red', size: 'medium' }; const userSettings = { color: 'blue' }; const combinedSettings = Object.assign({}, defaults, userSettings); console.log(combinedSettings); // 输出:{ color: 'blue', size: 'medium' }
Traps and precautions
The following are the pitfalls and problems that may be encountered when merging objects using the expand operator and the Object.assign()
method in JavaScript:
Expand operators and Object.assign()
both perform shallow copies when merging objects. This means that the nested object is still a reference to the original object. Modifying nested objects in merged objects may affect the original object, which may lead to unexpected side effects.
See Depth Merge below.
When merging objects with properties of the same key, the expand operator and Object.assign()
overwrite the values in the resulting object with the numeric value from the latest source object. If handled improperly, this behavior may lead to data loss.
The expansion operator is part of ECMAScript 2015 (ES6) and is not supported in older JavaScript environments or browsers such as Internet Explorer. This can cause compatibility issues if your code needs to run in an older environment. In this case, it is best to use Object.assign()
as it has wider support.
Expand operators and Object.assign()
will only copy the enumerable attributes from the source object to the target object. Non-enumerable properties are not copied during the merge process, which may lead to data loss or unexpected behavior.
If you need to merge large objects or perform merge operations frequently, using Object.assign()
or expand operators can cause performance issues because new objects are created during the merge process.
Object.assign()
Copy the attributes from the source object's prototype to the target object, which may lead to unexpected behavior if the source object's prototype has properties that conflict with the target object's properties. On the other hand, the expansion operator does not copy prototype properties.
Be sure to pay attention to these pitfalls and problems when using the expand operator or Object.assign()
in JavaScript. In certain cases, you may need to take other methods, such as deep cloning or deep merging functions, to overcome these limitations.
Which method to choose?
BothObject.assign()
and expand operators can effectively merge objects. The expand operator is simpler and more modern, while Object.assign()
is more compatible with older JavaScript environments.
To decide which method to use, consider:
Object.assign()
. Deep Merge: Deep Copy and Merge Objects
Expand operators and Object.assign()
both create shallow copies of the copied object. Essentially, this means that the new object will reference the same nested objects as the original object (such as arrays and functions), rather than a copy of them.
It is crucial to understand and avoid this before merging objects.
The following example shows how to edit a nested object of a copy object affects the original object:
const defaults = { color: 'red', size: 'medium' }; const userSettings = { color: 'blue' }; const combinedSettings = { ...defaults, ...userSettings }; console.log(combinedSettings); // 输出:{ color: 'blue', size: 'medium' }
This code shows that the shallowCopyPlanet
property of the original object planet
has been changed (you may not want this). info.moons
function accepts any number of input objects, creates a depth copy of them using the deepMergeObjects
technique, and then uses the expansion operation in the JSON.parse(JSON.stringify())
method to match them. The merged object will contain a depth copy of the properties from the input object. reduce()
const defaults = { color: 'red', size: 'medium' }; const userSettings = { color: 'blue' }; const combinedSettings = Object.assign({}, defaults, userSettings); console.log(combinedSettings); // 输出:{ color: 'blue', size: 'medium' }
Conclusion
Thank you for reading! I hope this article helps you gain insight into merging objects in JavaScript, not just a simple introduction. Being able to merge objects should combine well with your JavaScript skills and extend your coding capabilities. If you have any questions or comments, please join the SitePoint Community Forum.
FAQs on Merging Objects in JavaScript
What is the concept of merging objects in JavaScript?How to merge objects in JavaScript using the expansion operator?
) in JavaScript is a modern and efficient way to merge objects. It allows the expansion of iterable objects such as array expressions or strings for use where it is expected to be zero or more parameters or elements. Here is an example of how to use it: ...
const planet = { name: 'Earth', emoji: '?', info: { type: 'terrestrial', moons: 1 } }; // 使用展开运算符进行浅拷贝 const shallowCopyPlanet = { ...planet }; // 修改浅拷贝中的嵌套对象 shallowCopyPlanet.info.moons = 2; console.log('原始行星:', planet.info.moons); // 原始行星:2 console.log('行星的浅拷贝:', shallowCopyPlanet.info.moons); // 行星的浅拷贝:2
Object.assign()
Method is used to copy all enumerable values of one or more source objects to the target object. It will return the target object. It is a very useful way to merge objects because it allows you to merge multiple source objects into a single target object. However, it should be noted that if the same property is found in multiple objects, the value of the last object with that property will override the previous value. Object.assign()
Yes, you can merge nested objects in JavaScript. However, this process is a little more complicated because you need to make sure that nested objects are merged correctly, not just top-level properties. This is often called deep merge. The Object.assign()
and the expand operator do not perform deep merges by default. To do this, you need to implement custom functions or use libraries like Lodash.
When merging objects in JavaScript, if duplicate properties exist, the value of the last object will override the previous value. This is because when merging objects, it traverses the properties of the source object and assigns them to the target object. If an attribute already exists on the target object, its value will be replaced by the new value.
Yes, arrays can be merged in JavaScript using a similar method as an object. Expand operators are common ways to merge arrays. Here is an example:
const defaults = { color: 'red', size: 'medium' }; const userSettings = { color: 'blue' }; const combinedSettings = { ...defaults, ...userSettings }; console.log(combinedSettings); // 输出:{ color: 'blue', size: 'medium' }
Expand operator and Object.assign()
methods create a new object when merged, leaving the original object unchanged. This is a key feature of these methods because it promotes invariance, a core concept in functional programming where data never changes.
Yes, you can merge objects with different data types in JavaScript. The merged object will contain all the properties and methods of the original object regardless of its data type. However, if there are duplicate properties with different data types, the value of the last object will override the previous value.
Merging JavaScript objects can have performance impacts, especially when dealing with large objects. The time complexity of the expand operator and the Object.assign()
method is O(n), where n is the total number of properties in the source object. Therefore, when deciding to merge objects, it is important to consider the size of the object.
Yes, there are some libraries that can help merge objects in JavaScript. Lodash is a popular library that provides a range of utility functions for manipulating objects and arrays, including merge functions for deep merging objects. Another library is jQuery, which provides the $.extend()
method to merge objects.
The above is the detailed content of How to Merge Objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!