Home > Web Front-end > JS Tutorial > How Can I Merge Two JavaScript Objects?

How Can I Merge Two JavaScript Objects?

Mary-Kate Olsen
Release: 2024-12-21 09:38:11
Original
376 people have browsed it

How Can I Merge Two JavaScript Objects?

How to Merge Properties of Two JavaScript Objects

JavaScript does not provide a native method for merging objects directly. However, there are several ways to accomplish this task.

ECMAScript 2018 Standard Method

For ES2018 and later, the object spread syntax allows you to merge objects using the following code:

let merged = {...obj1, ...obj2};
Copy after login

Properties in obj2 will overwrite those in obj1. You can merge multiple objects using the same syntax.

ECMAScript 2015 (ES6) Standard Method

ES6 provides the Object.assign() method to merge objects. The first argument is the target object, while subsequent arguments are objects whose properties will be copied into the target:

Object.assign(obj1, obj2);

// Merge multiple objects
const allRules = Object.assign({}, obj1, obj2, obj3);
Copy after login

Method for ES5 and Earlier

For ES5 and earlier, you can use the following loop to merge objects:

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
Copy after login

This will simply add all attributes of obj2 to obj1, potentially overwriting existing properties.

Additional Notes

  • Object.assign() merges objects by reference, while the spread syntax creates a new object.
  • If you need more control over the merging process, you can create custom functions for this purpose.

The above is the detailed content of How Can I Merge Two JavaScript Objects?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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