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

问题描述 投票:9回答:4

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

underscore有可能做到以下几点吗? (我没有使用下划线,我只是希望它很简单)

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

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

var obj3 = merge(obj1, obj2);

/*

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

*/
javascript underscore.js
4个回答
14
投票

使用extend

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

第一个参数被修改,所以如果你不想修改obj1obj2只需传入{}


3
投票

这个将b合并为:

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

1
投票

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

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};
© www.soinside.com 2019 - 2024. All rights reserved.