gpt4 book ai didi

javascript - 如何使用 lodash 将对象中的数组数据与计数分组

转载 作者:行者123 更新时间:2023-12-02 23:11:04 25 4
gpt4 key购买 nike

如何使用 lodash javascript 对数据进行分组

"data": [
{
"id": 27,
"getOrderDetail": [
{
"id": 49,
"order_id": 27,
"product_id": 1,
"product_detail":[...some data...]
},
{
"id": 51,
"order_id": 27,
"product_id": 2,
"product_detail":[...some data...]
}
{
"id": 52,
"order_id": 27,
"product_id": 1,
"product_detail":[...some data...]
}
],
"getOrderStatus": []
},
]

我想在 getOrderDetail 中按 Product_id 进行分组,并将其计入数量,例如

"data": [
{
"id": 27,
"getOrderDetail": [
{
"id": 49,
"qty": 2,
"order_id": 27,
"product_id": 1,
"product_detail":[...some data...]
},
{
"id": 51,
"order_id": 27,
"qty": 1,
"product_id": 2,
"product_detail":[...some data...]
}
],
"getOrderStatus": []
},
]

我想做这样的事情

_.countBy(data, 'getOrderDetail.product_id'); 并将数据计数放入 qty 字段

这是我尝试的

let result = _.map(totalData, function(totalData, key) {
let mapData = _.groupBy(totalData.getOrderDetail, function({ product_id }) {
return product_id;
});
});

我的console.log(mapData)输出看起来像这样

{
'1': [
{
id: 49,
product_id: 1,
}
],
'2': [
{
id: 51,
product_id: 2,
}
]
}

仍然在寻找如何计算数量

最佳答案

您可以使用_.groupBy(),然后映射结果,并通过应用_.size()来获取qty组,并通过合并组成员、连接数组并传播回对象来获取 getOrderDetail:

const data = [{"id":27,"getOrderDetail":[{"id":49,"order_id":27,"product_id":1,"product_detail":[]},{"id":51,"order_id":27,"product_id":2,"product_detail":[]},{"id":52,"order_id":27,"product_id":1,"product_detail":[]}],"getOrderStatus":[]}];

const result = data.map(o => ({
...o,
getOrderDetail: _.map(
_.groupBy(o.getOrderDetail, 'product_id'),
group => ({
qty: _.size(groups),
..._.mergeWith({}, ...groups, (ov, sv) =>
_.isArray(ov) ? ov.concat(sv) : sv
)
})
)
}));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

关于javascript - 如何使用 lodash 将对象中的数组数据与计数分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357782/

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