Home > Web Front-end > JS Tutorial > How to Merge Objects in JavaScript

How to Merge Objects in JavaScript

William Shakespeare
Release: 2025-02-09 11:31:10
Original
270 people have browsed it

How to Merge Objects in JavaScript

Core points

  • Commonly used object merging methods in JavaScript include the expansion operator (...) 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.
  • 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 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 Merge Method
      1. Expand operator (...)
      1. 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' }
Copy after login
Copy after login
Copy after login

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' }
Copy after login
Copy after login

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?

Both

Object.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:

  1. If your environment supports expansion operators (such as the latest ECMAScript version), use it because it is syntactic.
  2. If compatibility with older JavaScript environments is critical, select Object.assign().
  3. 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' }
Copy after login
Copy after login
Copy after login
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

Custom Depth Merge Function

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' }
Copy after login
Copy after login

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
Copy after login

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' }
Copy after login
Copy after login
Copy after login

How to merge objects without modifying the original object?

The

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.

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template