Merge two objects and overwrite the values if conflict

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)


You can do it with Object.assign(), which is the internal language structure:

const o1 = {a: 1, b: 1, c:1};
const o2 = {b:5};
const o3 = Object.assign({}, o1, o2);

result:

o1: {a: 1, b: 1, c:1};
o2: {b: 5};
o3: {a: 1, b: 5, c:1};

Updated:

With ES6 you can do it more pretty by using spread:

const o3 = {...o1, ...o2}

you will create new object with properties from o1 merged with properties from o2 and updated from o2 on conflict properties names. This construction also doesn't need any extra libs or modules.