The Evolution of JS Object Merging

Jake Archibald made a tweet earlier today about cleverly using ECMAScript 2015 object destructuring to merge objects. That inspired this brief evolutionary summary of object merging in JS.

To exemplify lets first create three object literals as digital lab rats to eventually end up in our merged object.

// Declaring countries and carbs object for demo
const ireland = {
    Ireland: {
        carb: 'potato',
        capital: 'Dublin'   
    }
};

const usa = {
    USA: {
        carb: 'freedom fries',
        capital: 'Washington'    
    }
};

const china = {
    China: {
        carb: 'rice',
        capital: 'Beijing'    
    }
};

 

Way back

JQuery enabled simple object merging and gone were the days – more or less – of complex loops and manual property manipulation.

// Merging the good ol' jQuery way
const old = $.extend({}, ireland, usa, china);

 

Not too long ago

Eventually ES2015 appeared and enabled native browser support for object merging.

// Merging using ES2015 object assignment
const contemporary = Object.assign({}, ireland, usa, china);

 

Today

ES2015 enabled plenty of pure goodness and was a giant leap for the evolution of JavaScript. Destructuring and the spread syntax is the magic behind the modern way of object merging. Pure beauty! 🙂

// Merge like a boss
const modern = {...ireland, ...usa, ...china};

Finally, the merged object in all its glory using any of the above object merge techniques.

{
    "Ireland": {
        "carb": "potato",
        "capital": "Dublin"
    },
    "USA": {
        "carb": "freedom fries",
        "capital": "Washington"
    },
    "China": {
        "carb": "rice",
        "capital": "Beijing"
    }
}

 

1 Comment

Leave a Reply to Daniel P Cancel reply

Your email address will not be published.


*