0
votes

I am trying to do a for each on a database result set in Dataweave and not able to achieve the result.

Input payload:

{
    "x_orders_cursor": [{
        "LINE_QTY": 1,
        "ORDER_NUMBER": 11820490,
        "ORDERED_ITEM": "PAT1M",
        "LINE_UOM": "PC"
    }, {
        "LINE_QTY": 5000,
        "ORDER_NUMBER": 11820542,
        "ORDERED_ITEM": "ACC62-A-D",
        "LINE_NUMBER": 1,
        "LINE_UOM": "PC"
    }, {
        "LINE_QTY": 2000,
        "ORDER_NUMBER": 11820542,
        "ORDERED_ITEM": "ACC62-A-D",
        "LINE_NUMBER": 2,
        "LINE_UOM": "PC"
    }]
}

Expected Payload:

{
    "Orders": [
        {
            "OrderNum": "11820490",
            "Lines": [
                {
                    "LineNum": 1,
                    "ProductNum": "PAT1M",
                    "TxnQty": 1,
                    "TxnQtyUOM": "PC"
                }
            ]
        },
        {
            "OrderNum": "11820542",
            "Lines": [
                {
                    "LineNum": 1,
                    "ProductNum": "ACC62-A-D",
                    "TxnQty": 1000,
                    "TxnQtyUOM": "PC"
                },
                {
                    "LineNum": 2,
                    "ProductNum": "ACC62-A-D",
                    "TxnQty": 2000,
                    "TxnQtyUOM": "PC"
                }
            ]
        }
    ]
}

Result set is based on a database table that stores both Order Number and Line Number.

2

2 Answers

0
votes

You have to use groupBy for grouping line numbers from same order then map it. Please refer following code

%dw 1.0
%output application/json
---
Orders : payload.x_orders_cursor groupBy $.ORDER_NUMBER map {
    "OrderNum": $.ORDER_NUMBER[0],
        "Lines": $ map (LineDetails,index) ->{
            "LineNum": LineDetails.LINE_NUMBER default 1,
            "ProductNum": LineDetails.ORDERED_ITEM,
            "TxnQty": LineDetails.LINE_QTY,
            "TxnQtyUOM": LineDetails.LINE_UOM
        } orderBy $.LineNum
} orderBy $.OrderNum

I have used orderBy for ordering order and line items with order number and line numbers respectively

Hope this helps.

0
votes

Use the map and groupby operators to do this. Should be on below lines

payload groupBy $.ORDER_NUMBER map {
OrderNum: $.ORDER_NUMBER[0],
Lines": $ map (val,index) -> {
            LineNum: val.LINE_NUMBER default 1,
            ProductNum: val.ORDERED_ITEM,
            TxnQty: val.LINE_QTY,
            TxnQtyUOM: val.LINE_UOM
        } orderBy $.LineNum
} orderBy $.OrderNum