Use Case: When we have two arrays in different mule variables (or one in payload and one in variable), merge two arrays into a single array. We can use below dataweave logic to merge by an identifier.
Input:
Payload:
{
"orders": [
{
"id": 123,
"customer": "c1"
},
{
"id": 124,
"customer": "c2"
}
]
}
orderVar:
{
"orders": [
{
"id": 123,
"number": "xyz1"
},
{
"id": 124,
"number": "xyz2"
}
]
}
Dataweave:
%dw 2.0
output application/json
---
"orders":payload.orders map (record,index) -> {
(vars.orderVar.orders filter (record.id == $.id) map (record2,index2) -> {
"id": record.id,
"number": record2.number,
"customer": record.customer
})
}
Output:
{
"orders": [
{
"id": 123,
"number": "xyz1",
"customer": "c1"
},
{
"id": 124,
"number": "xyz2",
"customer": "c2"
}
]
}
In few scenarios we might need to merge by index of both input and output. Example, for salesforce bulk update/creates the response will be in the same order of the request payload. Here we should use index as an identifier. Below is the sample code.
%dw 2.0
output application/json
---
"orders":payload.orders map (record,index) -> {
(vars.orderVar.orders filter ($$ == index) map (record2,index2) -> {
"id": record.id,
"number": record2.number,
"customer": record.customer
})
}