合并两个对象并在冲突时覆盖值 [英] Merge two objects and overwrite the values if conflict

查看:30
本文介绍了合并两个对象并在冲突时覆盖值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

var obj1 = {"你好":"xxx"赢":xxx"};var obj2 = {"你好":"zzz"};var obj3 = 合并(obj1,obj2);/*{"你好":"zzz",赢":xxx"}*/

解决方案

你可以使用 Underscore 的扩展:

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

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

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

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

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

*/

解决方案

You could use Underscore's 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 {}.

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

UPDATE: Consider modern ES6 solutions (see other answers)

这篇关于合并两个对象并在冲突时覆盖值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆