How to Merge Properties of Two JavaScript Objects Dynamically

JavaScript provides several ways to merge properties of two objects dynamically. Whether you need to merge simple objects or complex ones, there are built-in methods and approaches that can help you achieve this. In this article, we will explore some of the commonly used techniques to merge properties of JavaScript objects at runtime.

1. Using the Spread Operator (ES6)

The spread operator is a concise syntax introduced in ES6 that allows us to expand elements of an iterable object (like an array or an object) into another object or array. We can use the spread operator to merge the properties of two objects by simply including them within curly braces. Let's see an example:

            
                const obj1 = { food: 'pizza', car: 'ford' };
                const obj2 = { animal: 'dog' };
                
                const mergedObj = { ...obj1, ...obj2 };
                
                console.log(mergedObj);
                // Output: { food: 'pizza', car: 'ford', animal: 'dog' }
            
        

In the example above, we used the spread operator to merge the properties of obj1 and obj2 into mergedObj. The resulting object contains all the properties from both objects.

It is important to note that the spread operator creates a shallow copy of the properties. If the objects being merged contain nested objects or arrays, changes to the nested objects or arrays in one object will affect the other. If you need a deep merge (where changes to nested objects/arrays do not affect the original objects), you can use alternative methods like the Object.assign() function or a custom recursive function.

2. Using the Object.assign() Method

The Object.assign() method is another way to merge properties of JavaScript objects. It takes one or more source objects and assigns their properties to a target object. Here's an example:

            
                const obj1 = { food: 'pizza', car: 'ford' };
                const obj2 = { animal: 'dog' };
                
                const mergedObj = Object.assign({}, obj1, obj2);
                
                console.log(mergedObj);
                // Output: { food: 'pizza', car: 'ford', animal: 'dog' }
            
        

In the example above, we used Object.assign() to merge the properties of obj1 and obj2 into mergedObj. The resulting object contains all the properties from both objects.

Just like the spread operator, the Object.assign() method performs a shallow copy. If you want to merge nested objects or arrays without affecting the original objects, you will need to use a custom recursive function.

3. Using a Custom Recursive Function

When dealing with nested objects or arrays, a custom recursive function provides more flexibility and control over the merging process. Here's an example of a simple recursive function to merge objects:

            
                function mergeObjects(obj1, obj2) {
                    for (let key in obj2) {
                        if (obj2.hasOwnProperty(key)) {
                            if (typeof obj2[key] === 'object') {
                                if (obj1.hasOwnProperty(key) && typeof obj1[key] === 'object') {
                                    mergeObjects(obj1[key], obj2[key]);
                                } else {
                                    obj1[key] = Array.isArray(obj2[key]) ? [] : {};
                                    mergeObjects(obj1[key], obj2[key]);
                                }
                            } else {
                                obj1[key] = obj2[key];
                            }
                        }
                    }
                    
                    return obj1;
                }
                
                const obj1 = { food: 'pizza', car: 'ford' };
                const obj2 = { animal: 'dog' };
                
                const mergedObj = mergeObjects(obj1, obj2);
                
                console.log(mergedObj);
                // Output: { food: 'pizza', car: 'ford', animal: 'dog' }
            
        

In the example above, we defined a recursive function mergeObjects() that takes two objects as arguments and merges their properties. The function iterates over the properties of obj2 and checks for nested objects. If a nested object is found, it recursively merges the nested objects. If a property is not a nested object, it is simply assigned to the corresponding key in obj1.

This custom recursive function allows you to merge nested objects without affecting the original objects. However, it requires careful handling of edge cases and may not be suitable for all scenarios.

Conclusion

Merging properties of JavaScript objects dynamically can be done using various methods and approaches. The choice of method depends on the complexity of the objects being merged and the desired outcome. The spread operator (...), Object.assign(), and custom recursive functions are some of the commonly used techniques.

The spread operator is a simple and concise way to merge properties, but it creates a shallow copy and does not handle nested objects. The Object.assign() method is another option that performs a shallow copy. If you need more control and flexibility, a custom recursive function is suitable for merging nested objects.

Experiment with these methods and choose the one that best fits your requirements. Happy coding!