How to Merge Objects in JavaScript
Core points
- Commonly used object merging methods in JavaScript include the expansion operator (
...
) and theObject.assign()
methods. The expand operator is more modern and concise, while theObject.assign()
is more compatible and suitable for older environments. - Expand operators and
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. - For deep merging (correctly merging nested objects), libraries such as custom functions or Lodash can be used. An example of a custom function
deepMergeObjects
is provided in the article, which creates a depth copy of the object before merging it using theJSON.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 Merge Method
-
- Expand operator (
...
)
- Expand operator (
-
-
Object.assign()
Method
-
-
- Traps and precautions
- Which method to choose
- Deep Merge: Deep Copy and Merge Objects
- Custom Depth Merge Function
- Conclusion
Object Merge Method
1. Expand operator (...
)
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' }
2. 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:
1. Shallow copy
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.
2. Override attributes
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.
3. Compatibility issues
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.
4. Non-enumerable attributes
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.
5. Performance issues
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.
6. Prototype properties
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:
- If your environment supports expansion operators (such as the latest ECMAScript version), use it because it is syntactic.
- If compatibility with older JavaScript environments is critical, select
Object.assign()
. - If you need to copy nested objects (necked objects of inner nested objects), read the deep copy object.
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
This is a function that deeply copies multiple objects before merging and returns a single object. In the code, the
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?Merging objects in JavaScript refers to the process of combining two or more objects into a single object. This is usually to merge properties and methods of multiple objects into one object, so that data can be managed and manipulated more easily. The merged object will contain all the properties and methods of the original object. If there are duplicate properties, the value of the last object will override the previous value.
How to merge objects in JavaScript using the expansion operator?
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
What is the role of methods in merging objects? 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()
Can I merge nested objects in JavaScript?
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.
What happens when merging objects, repeating attributes?
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.
Is it possible to merge arrays in JavaScript like merging objects?
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' }
How to merge objects without modifying the original object?
TheExpand 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.
Can I merge objects with different data types in JavaScript?
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.
What is the performance impact of merging JavaScript objects?
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.
What libraries can help merge objects in JavaScript?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
