In JavaScript, we can dynamically merge properties of two objects using multiple approaches. The most common methods involve the spread operator (...) and the Object.assign method. Below are examples illustrating both techniques:
Using the Spread Operator (...)
The spread operator enables us to concisely copy all enumerable properties from one object into a new object. Here is an example:
javascriptconst object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = { ...object1, ...object2 }; console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }
In this example, object1 and object2 are merged into mergedObject. Since both objects contain the property b, the value from object2 overrides the value from object1 because it is specified later in the spread operation.
Using the Object.assign Method
The Object.assign method copies all enumerable own properties from one or more source objects to a target object and returns the modified target object. Here is an example:
javascriptconst object1 = { a: 1, b: 2 }; const object2 = { b: 3, c: 4 }; const mergedObject = Object.assign({}, object1, object2); console.log(mergedObject); // Output: { a: 1, b: 3, c: 4 }
In the above example, we first create an empty object {} as the target, then copy properties from object1 and object2 into it. Similar to the spread operator, if duplicate properties exist, the later source objects override the earlier source objects' properties.
Key Considerations
When dynamically merging objects, note the following:
- Both the spread operator and
Object.assignperform a shallow copy. This means that if an object property is a complex type (e.g., an array or another object), the merged object shares the reference to this property with the source objects. - For deep copy merges, consider using a recursive strategy or a library like
lodash's_.mergefunction to ensure nested objects are also merged. - If merged objects contain duplicate properties, the values from later objects override those from earlier objects.
Selecting the appropriate merge strategy based on your application context is essential, and when handling large or complex objects, also evaluate performance and memory implications.