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' }The output of
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

Undress AI Tool
Undress images for free

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

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

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

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

The difference between var, let and const is scope, promotion and repeated declarations. 1.var is the function scope, with variable promotion, allowing repeated declarations; 2.let is the block-level scope, with temporary dead zones, and repeated declarations are not allowed; 3.const is also the block-level scope, and must be assigned immediately, and cannot be reassigned, but the internal value of the reference type can be modified. Use const first, use let when changing variables, and avoid using var.
