-1

I want to transform this data set:

[
        {
            "id": 470830,
            "input": "MANUAL",
            "value": 10000,
            "date": "2019-09-23T08:01:09.976Z"
        },
        {
            "id": 435258,
            "input": "AUTO",
            "value": 20000,
            "date": "2019-09-23T10:01:09.976Z"
        },
        {
            "id": 435207,
            "input": "MANUAL",
            "value": 5000,
            "date": "2019-09-24T12:01:09.976Z"
        },
        {
            "id": 435208,
            "input": "AUTO",
            "value": 15000,
            "date": "2019-09-24T14:01:09.976Z"
        }
]

to this

[
        {
            "date": "2019-09-23"
            "total": 30000,
            "manual": 10000,
            "auto": 20000,
        },
        {
            "date": "2019-09-24"
            "total": 20000,
            "manual": 5000,
            "auto": 15000,
        }
]

Objects are grouped by date (not DateTime) and remapped to have value props from AUTO and MANUAL + the sum of these.

What is the most efficient way to do this with JavaScript?

--- EDIT ---

Removed id on transformed object as a comment suggests

olefrank
  • 6,452
  • 14
  • 65
  • 90

1 Answers1

0

You can do:

const data = [{"id": 470830,"input": "MANUAL","value": 10000,"date": "2019-09-23T08:01:09.976Z"},{"id": 435258,"input": "AUTO","value": 20000,"date": "2019-09-23T10:01:09.976Z"},{"id": 435207,"input": "MANUAL","value": 5000,"date": "2019-09-24T12:01:09.976Z"},{"id": 435208,"input": "AUTO","value": 15000,"date": "2019-09-24T14:01:09.976Z"}]
const result = Object
  .values(data.reduce((acc, { id, input, value, date }) => {
    const ds = date.substring(0, 10)
    acc[ds] = acc[ds] || { id, auto: 0, manual: 0, value: 0, date: ds }
    acc[ds] = {
      id: acc[ds].id,
      date: ds,
      value: acc[ds].value + value,
      manual: input === 'MANUAL' ? acc[ds].manual + value : acc[ds].manual,
      auto: input === 'AUTO' ? acc[ds].auto + value : acc[ds].auto
    }
    return acc
  }, {}))

console.log(result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46