Skip to content

Merge two objects and overwrite the values if conflict

I’m trying to merge two objects and overwrite the values in the process.

Is it possible with underscore to do the following? (I’m fine with not using underscore I just want it to be simple)

var obj1 = {
    "hello":"xxx"
    "win":"xxx"
};

var obj2 = {
    "hello":"zzz"
};

var obj3 = merge(obj1, obj2);

/*

{
    "hello":"zzz",
    "win":"xxx"
}

*/

Answer

You could use Underscore’s extend:

 var obj3 = _.extend({}, obj1, obj2);

The first argument is modified, so if you don’t want to modify obj1 or obj2 just pass in {}.

Vanilla JS: const obj3 = Object.assign({}, obj1, obj2);

UPDATE: Consider modern ES6 solutions (see other answers)