Home >Web Front-end >JS Tutorial >How Can I Merge Two JavaScript Objects?
JavaScript does not provide a native method for merging objects directly. However, there are several ways to accomplish this task.
For ES2018 and later, the object spread syntax allows you to merge objects using the following code:
let merged = {...obj1, ...obj2};
Properties in obj2 will overwrite those in obj1. You can merge multiple objects using the same syntax.
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);
For ES5 and earlier, you can use the following loop to merge objects:
for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }
This will simply add all attributes of obj2 to obj1, potentially overwriting existing properties.
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!