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

问题描述 投票:0回答:1

我想使用lodash脚本对数据进行分组。首先,我尝试使用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: 2,
    machine_id: 2,
    work_id: 3,
    total: 10
  }
]

我想将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: 10
        },
          {
          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细分总和

javascript node.js
1个回答
0
投票

您可以尝试以下方法

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)
© www.soinside.com 2019 - 2024. All rights reserved.