lodash - 按键的两个对象的总和

时间:2018-03-12 15:31:39

标签: lodash

与先前提到的this问题相似,是否有一种简单的方法可以通过Lodash中的键来对两个对象或一组对象求和?

{ a:12, b:8, c:17 }

{ a:2, b:3, c:1 }

应该给出

{ a:14, b:11, c:18 }

2 个答案:

答案 0 :(得分:2)

您可以使用lodash的_.mergeWith()

var o1 = { a:12, b:8, c:17 };
var o2 = { a:2, b:3, c:1 };

var result = _.mergeWith({}, o1, o2, function(objValue, srcValue) {
  return _.isNumber(objValue) ? objValue + srcValue : srcValue; 
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

如果您知道所有值都是数字,或者您始终想要一起添加值,则可以使用_.add()作为合并自定义程序:

var o1 = { a:12, b:8, c:17, d: 'a' };
var o2 = { a:2, b:3, c:1, d: 'b' };

var result = _.mergeWith({}, o1, o2, _.add);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

要合并一个对象数组,请使用spread syntax_.mergeWith()

var arr = [{ a:12, b:8, c:17 }, { a:2, b:3, c:1 }];

var result = _.mergeWith({}, ...arr, function(objValue, srcValue) {
  return _.isNumber(objValue) ? objValue + srcValue : srcValue; 
});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

Array.reduce()

var arr = [{ a:12, b:8, c:17 }, { a:2, b:3, c:1 }];

var result = arr.reduce(function(r, o) {
  return  _.mergeWith(r, o, function(objValue, srcValue) {
    return _.isNumber(objValue) ? objValue + srcValue : srcValue; 
  });
}, {});

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.js"></script>

答案 1 :(得分:1)

一种解决方案是使用 assignWithadd

var o1 = { a:12, b:8, c:17 };
var o2 = { a:2, b:3, c:1 };

const combined = _.assignWith({}, o1, o2, _.add)

console.log(combined);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>