Search code examples
javascriptjsonnode-redjsonata

JSONata (or JS) - group and sum JSON array / objects


I want to 'groupsum' an array of objects with JSONata, from the following array:

payload = [
 {"id":"Irr-1","name":"Irrigation","timedif_s":7.743},
 {"id":"Irr-2","name":"Irrigation","timedif_s":2.749},
 {"id":"Lig-2","name":"Lights","timedif_s":1.475},
 {"id":"Irr-1","name":"Irrigation""timedif_s":1.07},]

The results must look like:

[{"name":"Irrigation", "sumtimedif": 11.562},
 {"name":"Lig-1", "sumtimedif": 1.475}]

I have tried:

payload.name{"name":payload.name,"sumtimedif":$sum(timedif_s)}

But I only get back an empty string.

{ empty }

Any advise?


Solution

  • The following JSONata expression will do this:

    payload{
      name: $sum(timedif_s)  /* group by name */
    } ~> $each(function($v, $k) {
     {"name": $k, "sumtimedif": $v}  /* transform each key/value pair */
    })
    

    The first part of the expression does the grouping and aggregation, and the second part transforms each group (key/value pair) into the format you want. http://try.jsonata.org/ByxzyQ0x4