使用Lodash按键求值

时间:2016-08-04 18:23:58

标签: javascript lodash

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

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

我正在寻找

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

1 个答案:

答案 0 :(得分:38)

这是每个独特元素的减少情况。

在应用缩减后,我总是使用_.groupBy然后_.map将结果用于数组。在这种情况下,缩减操作为_.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);

<script src="https://cdn.jsdelivr.net/lodash/4.14.1/lodash.min.js"></script>
&#13;
&#13;
&#13;