我希望通过创建一个新对象来合并两个对象,该对象包含在任一原始对象中出现的所有键,并指定合并键值的函数(如果不存在,则值应作为null / undefined传递在其中一个对象中。)
示例:
let foo = {"x": [1, 2], "y": [10, 11]};
let bar = {"x": [3, 4], "z": [22, 23]};
let merged = mergeByKey(foo, bar, (key, fooValue, barValue) => {
return (fooValue || []) + (barValue || []);
});
//merged = {"x": [1, 2, 3, 4], "y": [10, 11], "z": [22, 23]}
答案 0 :(得分:1)
你可以使用lodash#mergeWith
,它有一个iteratee决定用相同的键连接数组。
var merged = _.mergeWith(foo, bar, (v1, v2) => {
if(_.isArray(v1)) {
return v1.concat(v2);
}
});
let foo = {"x": [1, 2], "y": [10, 11]};
let bar = {"x": [3, 4], "z": [22, 23]};
var merged = _.mergeWith(foo, bar, (v1, v2) => {
if(_.isArray(v1)) {
return v1.concat(v2);
}
});
console.log(merged);

body > div { min-height: 100%; top: 0; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
答案 1 :(得分:0)
对于使用ImmutableJS的人
const { Map } = Immutable
const arrayMerger = (a,b) =>
Array.isArray(a) && Array.isArray(b) ? a.concat(b) : b
let foo = {"x": [1, 2], "y": [10, 11]}
let bar = {"x": [3, 4], "z": [22, 23]}
Map(foo).mergeDeepWith(arrayMerger, Map(bar)).toJS()
// {"x": [1, 2, 3, 4], "y": [10, 11], "z": [22, 23]}