Search code examples
dataweavemulesoft

how to groupBy flatboject array in dataweave


i have below array json which is from reading text/csv file . for example

[{
"no" : "2001",
"sendingStoreCode": "006091",
"receivingStoreCode": "006095",
"sku": "dddd",
"quantity": 1
},
{
"no" : "2001",
"sendingStoreCode": "006091",
"receivingStoreCode": "006095",
"sku": "xxxx",
"quantity": 1
},
{
"no" : "2002",
"sendingStoreCode": "006091",
"receivingStoreCode": "006095",
"sku": "xxxx",
"quantity": 1
}
]

now we have to groupBy #no, sendingStoreCode etc to merge data line, below is expected result ,may i know how to get it

[{
    "no": "2001",
    "sendingStoreCode": "006091",
    "receivingStoreCode": "006095",
    "deliveryItems": [{
            "line": 1,
            "sku": "dddd",
            "quantity": 1
        },
        {
            "line": 2,
            "sku": "xxxx",
            "quantity": 1
        }
    ]
}, {
    "no": "2002",
    "sendingStoreCode": "006091",
    "receivingStoreCode": "006095",
    "deliveryItems": [{
        "sku": "xxxx",
        "quantity": 1
    }]
}]

Solution

  • Maybe you can try something like this, notice that in the groupBy function, you have to create a single value that works as an id

    %dw 2.0
    output application/json
    ---
    payload 
      groupBy ((item, index) -> item.no ++ "-" ++ item.sendingStoreCode ++ "-" ++ item.receivingStoreCode)
      pluck ((value, key, index) -> {
          no: value.no[0],
          sendingStoreCode: value.sendingStoreCode[0],
          receivingStoreCode: value.receivingStoreCode[0],
          deliveryItems: value map ((item, index) -> {
            "line" : index + 1,
            "sku": item.sku,
            "quantity": item.quantity
          })
      })