Javascript 使用 Lodash 按键对值求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38774763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:49:51  来源:igfitidea点击:

Using Lodash to sum values by key

javascriptlodash

提问by S. Hussey

How can I sum the values in objects which share a common key? I needto use Lodash for this because I need good performance if these arrays get huge.

如何对共享公共键的对象中的值求和?我需要为此使用 Lodash,因为如果这些数组变得很大,我需要良好的性能。

var prjMgrValues = [
   {"proj_mgr":"Hyman ProjManager","submitted_dollars":12000},
   {"proj_mgr":"Hyman ProjManager","submitted_dollars":750000},
   {"proj_mgr":"Joe ProjManager","submitted_dollars":45000}
]

I'm looking for an output of

我正在寻找输出

[
  {"proj_mgr":"Hyman ProjManager","submitted_dollars":762000},
  {"proj_mgr":"Joe ProjManager","submitted_dollars":45000}
]

回答by 4castle

This is a case of reduction for each unique element.

这是对每个唯一元素进行归约的情况。

I always use _.groupByand then _.mapthe result to an array after applying the reduction. In this case the reduction operation is _.sumBy.

我总是使用_.groupBy然后_.map在应用减少后将结果转换为数组。在这种情况下,归约操作是_.sumBy

var prjMgrValues = [
   {"proj_mgr":"Hyman ProjManager","submitted_dollars":12000},
   {"proj_mgr":"Hyman ProjManager","submitted_dollars":750000},
   {"proj_mgr":"Joe ProjManager","submitted_dollars":45000}
];

var output =
  _(prjMgrValues)
    .groupBy('proj_mgr')
    .map((objs, key) => ({
        'proj_mgr': key,
        'submitted_dollars': _.sumBy(objs, 'submitted_dollars') }))
    .value();

console.log(output);
<script src="https://cdn.jsdelivr.net/lodash/4.14.1/lodash.min.js"></script>