Merge two objects and rewrite the values ​​if they conflict

I am trying to combine two objects and overwrite the values ​​in this process.

Is it possible to do the following with underscore ? (I'm fine, not using underscores, 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" } */ 
+9
javascript
source share
3 answers

Use extend :

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

The first argument is changed, so if you do not want to change obj1 or obj2 , just go to {} .

+14
source share

This combines 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 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); 
+3
source share

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

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

result:

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

All Articles