如何使用lodash合并包含数组和其他字段的两个对象?
例如,
obj1 = {
name: "abc",
hobbies: ["reading","cricket"]
}
obj2 = {
name: "abc2",
hobbies: ["reading","hockey"]
}
_.merge(obj1, obj2)
// output
{
name: "abc2",
hobbies: ["reading","hockey"]
}
这会在将obj1合并到obj2之后返回一个对象,但不会合并这些爱好。
答案 0 :(得分:3)
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。