合并包含数组的对象

时间:2015-01-07 20:12:39

标签: javascript lodash

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

例如,

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

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

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

1 个答案:

答案 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