Using Lodash to sum values by key

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

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

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

I'm looking for an output of

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

回答1:

This is a case of reduction for each unique element.

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

var prjMgrValues = [    {"proj_mgr":"Jack ProjManager","submitted_dollars":12000},    {"proj_mgr":"Jack 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);


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!