Merge two objects and overwrite the values if conflict

﹥>﹥吖頭↗ 提交于 2020-07-15 04:30:22

问题


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

*/

回答1:


Use 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 {}.




回答2:


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}



回答3:


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);



回答4:


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.



来源:https://stackoverflow.com/questions/17972473/merge-two-objects-and-overwrite-the-values-if-conflict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!