Tuesday, 19 November 2024

Merging JavaScript Objects: Techniques and Examples

 Merging properties of JavaScript objects is a common task when dealing with dynamic data structures. In this post, we’ll explore different ways to merge objects in JavaScript, showcasing various examples and techniques suitable for flat objects without recursion or functions.

1. Using the Spread Operator

The spread operator (...) is a modern and concise way to merge objects introduced in ECMAScript 2018. It creates a new object containing the properties of both input objects. If there are duplicate keys, the values from the second object overwrite those in the first.

const obj1 = { color: 'blue', size: 'large' };
const obj2 = { material: 'cotton', size: 'medium' };

const merged = { ...obj1, ...obj2 };

console.log(merged);
// Output: { color: 'blue', size: 'medium', material: 'cotton' }

Here, the size property in obj2 overwrites the value in obj1.

2. Using Object.assign()

Introduced in ECMAScript 2015, Object.assign() merges objects by copying properties from one or more source objects into a target object. Unlike the spread operator, Object.assign() directly mutates the first argument.

const obj1 = { city: 'Paris', country: 'France' };
const obj2 = { population: '2M', city: 'Lyon' };

Object.assign(obj1, obj2);

console.log(obj1);
// Output: { city: 'Lyon', country: 'France', population: '2M' }

To avoid modifying the original objects, you can pass an empty object as the first argument:

const merged = Object.assign({}, obj1, obj2);
console.log(merged);
// Output: { city: 'Lyon', country: 'France', population: '2M' }

3. Merging with a Custom Function

For greater control, you can write a function to merge two objects. This approach avoids mutating the original objects and allows customization.

function mergeObjects(obj1, obj2) {
    const result = { ...obj1 };
    for (const key in obj2) {
        if (obj2.hasOwnProperty(key)) {
            result[key] = obj2[key];
        }
    }
    return result;
}

const obj1 = { sport: 'soccer', team: 'Barcelona' };
const obj2 = { player: 'Messi', sport: 'tennis' };

const merged = mergeObjects(obj1, obj2);
console.log(merged);
// Output: { sport: 'tennis', team: 'Barcelona', player: 'Messi' }

This method ensures no unintended prototype properties are included.

4. Using jQuery’s extend Method

If you’re already using jQuery, its $.extend utility can merge objects, with support for both shallow and deep merging.

const obj1 = { name: 'Alice', age: 30 };
const obj2 = { age: 25, hobby: 'cycling' };

const merged = $.extend({}, obj1, obj2);
console.log(merged);
// Output: { name: 'Alice', age: 25, hobby: 'cycling' }

To enable deep merging of nested objects, pass true as the first argument:

const obj1 = { preferences: { theme: 'dark', notifications: true } };
const obj2 = { preferences: { theme: 'light' } };

const merged = $.extend(true, {}, obj1, obj2);
console.log(merged);
// Output: { preferences: { theme: 'light', notifications: true } }

5. Using a Polyfill for Object.assign()

If you need to support older browsers that lack Object.assign(), you can implement a simple polyfill:

if (typeof Object.assign !== 'function') {
    Object.assign = function(target, ...sources) {
        sources.forEach(source => {
            for (const key in source) {
                if (Object.prototype.hasOwnProperty.call(source, key)) {
                    target[key] = source[key];
                }
            }
        });
        return target;
    };
}

const obj1 = { framework: 'React' };
const obj2 = { framework: 'Vue', version: '3.0' };

const merged = Object.assign({}, obj1, obj2);
console.log(merged);
// Output: { framework: 'Vue', version: '3.0' }

6. Deep Merging with Libraries

For more complex scenarios involving nested objects, consider using libraries like Lodash or deepmerge. Here’s an example using deepmerge:

import merge from 'deepmerge';

const obj1 = { settings: { mode: 'auto', brightness: 50 } };
const obj2 = { settings: { brightness: 80, contrast: 70 } };

const merged = merge(obj1, obj2);
console.log(merged);
// Output: { settings: { mode: 'auto', brightness: 80, contrast: 70 } }

Choosing the Right Method

  • Use the spread operator or Object.assign() for shallow merging.
  • Use custom functions for controlled merging without external dependencies.
  • Use jQuery’s extend or deepmerge for complex scenarios requiring deep merging.

Experiment with these techniques to find the one that best suits your use case!

Labels:

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home