gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:10:12 26 4
gpt4 key购买 nike

我有以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com