javascript - 我如何使用 lodash 根据某个键总结集合

标签 javascript lodash

我有以下 Json 数据,我想合并具有相同 customer_id 的记录,因此每个 customer_id 有一条记录

  [
   {
      "id":2,
      "customer_id":2,
      "amount":50,
      "total":100,
      "currency_code":"USD",
      "customer":{
         "id":2,
         "name":"ABC Company",
         "latest_comment":null
      }
   },
   {
      "id":3,
      "customer_id":3,
      "amount":90,
      "total":60,
      "currency_code":"USD",
      "customer":{
         "id":3,
         "name":"ABC Company 1"
      }
   },
   {
      "id":7,
      "customer_id":3,
      "amount":10,
      "total":40,
      "currency_code":"USD",
      "customer":{
         "id":3,
         "name":"ABC Company 1"
      }
   }
 ]

在此示例中,有两个 customer_id = 3 的对象(第二个和第三个)

我想按 customer_id 汇总行,因此结果集合看起来像

   [
       {
          "id":2,
          "customer_id":2,
          "amount":50,
          "total":100,
          "currency_code":"USD",
          "customer":{
             "id":2,
             "name":"ABC Company",
             "latest_comment":null
          }
       },
       {
          "id":null,             //just because there are multiple rows with same customer_id
          "customer_id":3,
          "amount":100,
          "total":100,
          "currency_code":"USD",
          "customer":{
             "id":3,
             "name":"ABC Company 1"
          }
       }
   ]

最佳答案

您可以使用以下代码来获取总和:

var arr = [{
    "id": 2,
    "customer_id": 2,
    "amount": 50,
    "total": 100,
    "currency_code": "USD",
    "customer": {
      "id": 2,
      "name": "ABC Company",
      "latest_comment": null
    }
  },
  {
    "id": 3,
    "customer_id": 3,
    "amount": 90,
    "total": 60,
    "currency_code": "USD",
    "customer": {
      "id": 3,
      "name": "ABC Company 1"
    }
  },
  {
    "id": 7,
    "customer_id": 3,
    "amount": 10,
    "total": 40,
    "currency_code": "USD",
    "customer": {
      "id": 3,
      "name": "ABC Company 1"
    }
  }
]

var output =
  _(arr)
  .groupBy('customer_id')
  .map((objs, key) => ({

    'customer_id': key,
    'amount': _.sumBy(objs, 'amount'),
    'total': _.sumBy(objs, 'total')

  }))
  .value();

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

_.groupBy返回给定字段的聚合对象和

_.sumBy返回迭代给定字段和数组的总和。

关于javascript - 我如何使用 lodash 根据某个键总结集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45901682/

相关文章:

javascript - js 列出对象的路径信息

javascript - JS : getElementByID wildcard

javascript - 底部验证失败,为什么浏览器显示在页面顶部?

javascript - 根据用户代理更改样式表

javascript - 类型安全的嵌套属性查找

node.js - 如何修复 Seriate 和 Lodash 漏洞

javascript - 数组过滤元素彼此的值太接近

javascript - lodash 中的 transform 和 reduce 有什么区别

javascript - MouseEvent.path 在 Firefox 和 Safari 中等效

javascript - 从数组中获取三个最小值