How to combine two JSON payload in Mule 4 Dataweave 2.0

Consider a scenario where you might need to merge or combine two JSON arrays & send it as a response. In this case, we need to merge the data using a common key available in both messages.
Merge two JSON array into a single JSON array using Dataweave 2.0
Input 1:
{
"users": [
{
"userId": 1,
"firstName": "Uday",
"lastName": "Kiran",
"role": "Developer",
"phoneNumber": "930293029",
"emailAddress": "hello@designgrows.com"
},
{
"userId": 2,
"firstName": "Jake",
"lastName": "Anderson",
"role": "Developer",
"phoneNumber": "7567567567",
"emailAddress": "jake@google.com"
}
]
}
Input 2:
"skillsList": [
{
"skillID": 1,
"skillName": "MuleSoft"
},
{
"skillID": 2,
"skillName": "Java"
}
]
Expected Output:
[
{
"userId": 1,
"firstName": "Uday",
"skillName": "MuleSoft"
},
{
"userId": 2,
"firstName": "Jake",
"skillName": "Java"
}
]
Also see: Importing a Mapping File in a DataWeave Script of Mule
Combine two JSON array fields into one JSON array using Dataweave 2.0
Dataweave Code:
payload.users map (key,val)-> {
"userId": key.userId,
"firstName": key.firstName,
(skills.skillsList filter ($."skillID" == key."userId") map ((k,v) -> {
skillName: k.skillName
}))
}
Output:

Also read: Simple use of filter, contains in Dataweave 2.0 on JSON message
0 Comments