I want to group data using lodash javscript. first I try to use groupBy machine_id then I sum the total value
Here is my data
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
},
]
I want to group machine_id then I want to sum by machine_id and after that I want to sum total each work_id
I want to output like this
[
{
"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
}
]
},
]
This is what I try
let groupData = _(data)
.groupBy("machine_id")
.map((data, machine_id) => ({
machine_id,
sum_total: _.sumBy(data, item => Number(item.total_time))
}))
.value();
my output look like this :
[
{
"machine_id": 1,
"sum_total": 25
},
{
"machine_id": 2,
"sum_total": 10
},
]
How can I drill down sum by work_id