1

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

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I hadn't seen the flatMap, I had been looking at flatten. Thanks for your help.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.