0

I'm looking for an output similar to this one below where i want to groupBy costomer and orderid.

Input:

[
    {
        "item": 621,
        "orderid": "ON22",
        "qty": 45.0,
        "customer": "813",
        "date": "1988-08-13"
    },
  {
        "item": 63,
        "orderid": "ON22",
        "qty": 7,
        "customer": "813",
        "date": "2001-08-13"
    },
 {
        "item": 54,
        "orderid": "AD546",
        "qty": 9,
        "customer": "813",
        "date": "2014-08-13"
    },
   {
        "item": 611,
        "orderid": "ON222723-JH",
        "qty": 78.0,
        "customer": "890",
        "date": "1990-05-11"
    }
]

Desired output:

[
   {
      "customer":"890",
       "orderid":"ON222723-JH",
      "data":[
         {
            "item":611,
            "qty":78.0,
            "date":"1990-05-11"
         }
      ]
   },
   {
      "customer":"813",
        "orderid":"ON22",
      "data":[
         {
            "item":621,
            "qty":45.0,
            "date":"1988-08-13"
         },
       {
       "item": 63,
        "qty": 7,
        "date": "2001-08-13"
      }
      ]
   },
   {
      "customer":"813",
       "orderid":"AD546",
      "data":[
         {
         "item": 54,
        "qty": 9,
        "date": "2014-08-13"
         }
      ]
   }
]

1 Answer 1

2

I usually use the trick of concating the keys I need in groupBy to achieve what you need.

%dw 2.0
output application/json

// Concat customer and ordered as the key to group the items. Use a character that can't be part of any of the fields.
var groupedOrders = payload groupBy ((item, index) -> item.customer ++ "|" ++ item.orderid)
---
valuesOf(groupedOrders) map ((items, index) -> 
    {
        // I'm getting the first element as all in the items collection should have the same customer and orderid
        "customer": items[0].customer, 
        "orderid": items[0].orderid, 
        // The map here is just to remove the repeated fields
        "data": items map ((item, index) -> item - "customer" - "orderid")
    }
)
1
  • Just to be consistent with the output, you would want to add orderBy (-$.customer) before the groupBy.
    – Salim Khan
    Sep 23, 2022 at 14:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.