[英]How can I group array data in object using lodash javascript
我想使用 lodash javscript 对数据进行分组。 首先我尝试使用 groupBy machine_id 然后我总结总价值
这是我的数据
const data = [
{
id: 1,
machine_id: 1,
work_id: 1,
total: 10
},
{
id: 2,
machine_id: 1,
work_id: 2,
total: 15
},
{
id: 3,
machine_id: 2,
work_id: 3,
total: 10
},
{
id: 4,
machine_id: 1,
work_id: 1,
total: 15
},
]
我想对 machine_id 进行分组,然后我想通过 machine_id 求和,然后我想对每个 work_id 求和
我想这样输出
[
{
"machine_id": 1,
"sum_total": 25
"work_group": [
// In this work group I want to sum total each work_id
{
work_id: 1
sum_total: 25
},
{
work_id: 2
sum_total: 15
}
]
},
{
"machine_id": 2,
"sum_total": 10
"work_group": [
{
work_id: 3
sum_total: 10
}
]
},
]
这就是我尝试的
let groupData = _(data)
.groupBy("machine_id")
.map((data, machine_id) => ({
machine_id,
sum_total: _.sumBy(data, item => Number(item.total_time))
}))
.value();
我的输出是这样的:
[
{
"machine_id": 1,
"sum_total": 25
},
{
"machine_id": 2,
"sum_total": 10
},
]
如何通过 work_id 向下钻取总和
用户reduce
和Object.values
将简化
const data = [ { id: 1, machine_id: 1, work_id: 1, total: 10 }, { id: 2, machine_id: 1, work_id: 2, total: 15 }, { id: 3, machine_id: 2, work_id: 3, total: 10 }, { id: 4, machine_id: 1, work_id: 1, total: 15 } ]; const updated = Object.values( data.reduce((acc, curr) => { if (curr.machine_id in acc) { const work_group = [ ...acc[curr.machine_id].work_group, { work_id: curr.work_id, sum_total: curr.total } ].reduce((wg_acc, wg_curr) => { wg_acc[wg_curr.work_id] = wg_curr.work_id in wg_acc ? { ...wg_acc[wg_curr.work_id], sum_total: wg_acc[wg_curr.work_id].sum_total + wg_curr.sum_total } : { ...wg_curr }; return wg_acc; }, {}); acc[curr.machine_id] = { ...acc[curr.machine_id], sum_total: acc[curr.machine_id].sum_total + curr.total, work_group: Object.values(work_group) }; } else { acc[curr.machine_id] = { machine_id: curr.machine_id, sum_total: curr.total, work_group: [{ work_id: curr.work_id, sum_total: curr.total }] }; } return acc; }, {}) ); console.log(updated);
您可以尝试以下方法
const data = [ { id: 1, machine_id: 1, work_id: 1, total: 10 }, { id: 2, machine_id: 1, work_id: 2, total: 15 }, { id: 2, machine_id: 2, work_id: 3, total: 10 } ] const res = data.reduce((acc = [], obj) => { const data = acc.findIndex(d => d.machine_id === obj.machine_id) if(data > -1) { acc[data] = { ...data, sum_total: acc[data].sum_total + obj.total, work_group: [...acc[data].work_group, obj] } } else { acc.push({ machine_id: obj.machine_id, sum_total: obj.total, work_group:[obj] }) } return acc; }, []) console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.