合并两个对象并在发生冲突时覆盖值

时间:2013-07-31 13:57:37

标签: javascript underscore.js

我正在尝试合并两个对象并覆盖过程中的值。

underscore可以执行以下操作吗? (我没有使用下划线,我只是希望它很简单)

var obj1 = {
    "hello":"xxx"
    "win":"xxx"
};

var obj2 = {
    "hello":"zzz"
};

var obj3 = merge(obj1, obj2);

/*

{
    "hello":"zzz",
    "win":"xxx"
}

*/

4 个答案:

答案 0 :(得分:14)

使用extend

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

修改了第一个参数,因此如果您不想修改obj1obj2,只需传入{}

答案 1 :(得分:3)

这个将b 合并到 a:

function merge(a, b) {
    for(var idx in b) {
        a[idx] = b[idx];
    } //done!
}

merge(a, b); //a is merged

甚至:

Object.prototype.myMerge = function(b) {
    for(var idx in b) {
        this[idx] = b[idx];
    } //done!
};

a.myMerge(b); //a is merged

这个返回一个合并对象:

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

答案 2 :(得分:1)

在ES6或Typescript中使用对象传播

您还可以将一个对象散布到另一个对象中。一个常见的用例是简单地向对象添加属性,而无需更改原始对象:

const point2D = {x: 1, y: 2};
/** Create a new object by using all the point2D props along with z */
const point3D = {...point2D, z: 3};

对于对象,价差的放置顺序很重要。它的工作方式类似于Object.assign,并且可以实现您所期望的:先出现的内容被后来的内容“覆盖”:

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 :(得分:0)

您可以使用Object.assign()(内部语言结构)来完成此操作:

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

结果:

o1: {a: 1, b: 1, c:1};
o2: {b: 5};
o3: {a: 1, b: 5, c:1};
相关问题