16

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

下划线是否可以执行以下操作?(我可以不使用下划线我只是希望它简单)

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

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

var obj3 = merge(obj1, obj2);

/*

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

*/
4

4 回答 4

20

您可以使用下划线的 extend

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

第一个参数被修改了,所以如果你不想修改obj1或者obj2只是传入{}.

香草JS: const obj3 = Object.assign({}, obj1, obj2);

更新:考虑现代 ES6 解决方案(参见其他答案)

于 2013-07-31T14:00:21.733 回答
10

您可以使用Object.assign(),这是内部语言结构:

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

结果:

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

更新

使用ES6,你可以通过使用 spread 来做的更漂亮:

const o3 = {...o1, ...o2}

您将创建新对象,其中 o1 的属性与 o2 的属性合并,并根据冲突属性名称从 o2 更新。这种结构也不需要任何额外的库或模块。

于 2019-01-16T15:57:08.693 回答
5

在 ES6 或 Typescript 中使用 Object spread

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

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}
于 2019-03-15T08:57:08.637 回答
4

这将 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);
于 2013-07-31T13:59:00.893 回答