如何使用lodash合并两个包含数组和其他字段的对象?

例如,

obj1 = {
    name: "abc",
    hobbies: ["reading","cricket"]
}
obj2 = {
    name: "abc2",
    hobbies: ["reading","hockey"]
}
_.merge(obj1, obj2)

// output
{
    name: "abc2",
    hobbies: ["reading","hockey"]
}


这将obj1合并到obj2后返回一个对象,但不合并这些兴趣爱好。

最佳答案

Underscore.js没有_.merge函数,所以我假设您正在使用Lo-Dash。如果是这种情况,可以使用callback参数执行所需的操作

var obj1 = { name: 'abc', hobbies: ['reading', 'cricket'] };
var obj2 = { name: 'def', hobbies: ['reading', 'hockey'] };

var output = _.merge(obj1, obj2, function(a,b) {
    return _.isArray(a) ? _.union(a,b) : undefined;
} );
console.log( output );

// output

{ name: 'def', hobbies: ['reading', 'cricket', 'hockey'] }


编辑

工作JSFiddle

09-19 02:11