dataweavemule4

How to groupBy two field in dataweave 2.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"
         }
      ]
   }
]

Solution

  • **Another way of doing it without using groupBy**
    
    %dw 2.0
    output application/json
    import * from dw::core::Arrays
    ---
    (payload map ((item, index) -> 
    {
        customer:item.customer,
        orderid: item.orderid,
        data: (payload filter ((item2, index2) -> (item.customer== item2.customer) and (item.orderid==item2.orderid) )) map ((item3, index3) -> {
            item: item3.item,
            qty: item3.qty,
            date: item3.date
        })
    })) orderBy ((item4, index4) -> item4.customer[-1])