Search code examples
anypoint-studiodataweavemulesoft

Merge fields from multiple nested arrays in JSON input into new payload array using Dataweave


I am using Anypoint Studio 7.3 and Mule 4.2.

Using the JSON input below, I would like to create new payloads to write to database tables including a payload which builds a list of customers from each record entry in the array to create a list entry looking like this:

[{
    recordId,
    customerId
}]

and the same for a list of transactions with each list entry looking like this:

[{
     recordId
     customerId
     transactionId
}]

but when I try to transform the data the field values show either as null or as a list instead of a single field in the object like this:

{
    "customers": [{
        "record": "1234",  
        "customerId": [
            "5435e1cd-146d-4aac-9164-4a2d80d5eccd"
        ]
    }]
}

instead of this:

{
    "customers": [{
        "recordId": "1234",
        "customerId": "5435e1cd-146d-4aac-9164-4a2d80d5eccd"
    }]
}

JSON INPUT:

{
    "records": [{
        "recordId": "1234",
        "customers": [{
            "customerId": "1234",
            "transactions": [{
                "transactionId": "1234",
                "prices": [{
                    "priceId": "1234",
                    "price": 1.00
                }]
            }]
        }]
    }]
}

Thanks for any help


Solution

  • In order to return the list of customers from each record

    %dw 2.0
    output application/java
    ---
    payload.records flatMap 
        ((record, index) -> 
            record.customers map ((customer, index) -> 
                {
                  recordId: record.recordId,
                  customerId: customer.customerId          
                }
            )
        )
    

    And for returning list of transactions with each list entry

    %dw 2.0
    output application/json
    ---
    payload.records flatMap 
        ((record, index) -> 
            record.customers flatMap ((customer, index) -> 
                customer.transactions map ((transaction, index) -> 
                    {
                        recordId: record.recordId,
                        customerId: customer.customerId,
                        transactionId: transaction.transactionId        
                    }
                )
            )
        )
    

    The key part here is using flatMap for flattening nesting levels of arrays into one.