Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How can I merge properties of two JavaScript objects dynamically?
To merge properties of two JavaScript objects dynamically, you can use the spread operator ({...object1, ...object2}) or Object.assign(). Both methods create a new object containing properties from multiple source objects.
Using Spread Operator (Recommended)
The spread operator is the modern and most concise approach:
var firstObject = {
firstName: 'John',
lastName: 'Smith'
};
var secondObject = {
countryName: 'US'
};
var mergedObject = {...firstObject, ...secondObject};
console.log(mergedObject);
{ firstName: 'John', lastName: 'Smith', countryName: 'US' }
Using Object.assign()
An alternative method using Object.assign():
var obj1 = { name: 'Alice', age: 30 };
var obj2 = { city: 'New York', country: 'USA' };
var obj3 = { hobby: 'reading' };
var merged = Object.assign({}, obj1, obj2, obj3);
console.log(merged);
{ name: 'Alice', age: 30, city: 'New York', country: 'USA', hobby: 'reading' }
Handling Property Conflicts
When objects have the same property names, the rightmost object's values take precedence:
var obj1 = { name: 'John', age: 25 };
var obj2 = { age: 30, city: 'Boston' };
var merged = {...obj1, ...obj2};
console.log(merged);
{ name: 'John', age: 30, city: 'Boston' }
Comparison
| Method | Syntax Complexity | Browser Support | Performance |
|---|---|---|---|
| Spread Operator | Simple | ES2018+ | Fast |
| Object.assign() | Moderate | ES2015+ | Good |
Conclusion
Use the spread operator for simple object merging as it's more readable and concise. Both methods create shallow copies, so nested objects are shared by reference.
Advertisements
