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

How Can I Merge JavaScript Objects?

DDD
Release: 2024-12-25 04:33:17
Original
816 people have browsed it

How Can I Merge JavaScript Objects?

How Can JavaScript Objects Be Merged?

Merging objects in JavaScript involves combining properties from multiple objects into a single unified object. To achieve this, several methods are available, each suitable for specific JavaScript versions and requirements.

Built-in Methods

ECMAScript 2018 Standard Method: Utilizing object spread, the new syntax for merging objects is:

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

This syntax creates a new merged object that contains the combined properties of obj1 and obj2. Properties in obj2 overwrite those in obj1.

ECMAScript 2015 Standard Method: Object.assign() can be used to merge objects:

Object.assign(obj1, obj2);
Copy after login

Object.assign() modifies obj1 in place, merging the properties of obj2 into it. As with the spread operator, later properties overwrite earlier ones.

Method for ES5 and Earlier

For JavaScript versions prior to ES5, a straightforward approach is:

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

This loop iterates through the properties of obj2 and assigns them to obj1, effectively merging the objects.

Custom Function

A custom function can also be employed:

function merge_options(obj1, obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}
Copy after login

This function creates a new object obj3 by iterating through obj1 and obj2, adding the properties to obj3.

The above is the detailed content of How Can I Merge 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template