Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}

*/
like image 909
ThomasReggi Avatar asked Jul 31 '13 13:07

ThomasReggi


2 Answers

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)

like image 118
Paul Avatar answered Sep 26 '22 02:09

Paul


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.