Reputation: 59365
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"
}
*/
Upvotes: 22
Views: 22330
Reputation: 24775
in ES6 or Typescript use Object spread
You can also spread an object into another object. A common use case is to simply add a property to an object without mutating the original:
const point2D = {x: 1, y: 2};
/** Create a new object by using all the point2D props along with z */
const point3D = {...point2D, z: 3};
For objects, the order of where you put the spread matters. This works something like Object.assign
, and does what you'd expect: what comes first is 'overridden' by what comes later:
const point2D = {x: 1, y: 2};
const anotherPoint3D = {x: 5, z: 4, ...point2D};
console.log(anotherPoint3D); // {x: 1, y: 2, z: 4}
const yetAnotherPoint3D = {...point2D, x: 5, z: 4}
console.log(yetAnotherPoint3D); // {x: 5, y: 2, z: 4}
Upvotes: 9
Reputation: 141829
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)
Upvotes: 23
Reputation: 429
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.
Upvotes: 22
Reputation: 146310
This one merges b into a:
function merge(a, b) {
for(var idx in b) {
a[idx] = b[idx];
} //done!
}
merge(a, b); //a is merged
Or even:
Object.prototype.myMerge = function(b) {
for(var idx in b) {
this[idx] = b[idx];
} //done!
};
a.myMerge(b); //a is merged
This one returns a merged object:
function merge(a, b) {
var c = {};
for(var idx in a) {
c[idx] = a[idx];
}
for(var idx in b) {
c[idx] = b[idx];
}
return c;
}
var c = merge(a, b);
Upvotes: 4