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"
}
*/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With