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.
ECMAScript 2018 Standard Method: Utilizing object spread, the new syntax for merging objects is:
let merged = {...obj1, ...obj2};
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);
Object.assign() modifies obj1 in place, merging the properties of obj2 into it. As with the spread operator, later properties overwrite earlier ones.
For JavaScript versions prior to ES5, a straightforward approach is:
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
This loop iterates through the properties of obj2 and assigns them to obj1, effectively merging the objects.
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; }
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!