DataWeave Interview Question: Compare IDs From Two Arrays and Create a New Array
This article will help you practice your DataWeave skills in MuleSoft. We're going to compare IDs from two arrays of objects and create a new array.
Join the DZone community and get the full member experience.
Join For FreeThis article will help you practice your DataWeave skills in MuleSoft. Let's get started.
Input:
1)
[
{
name : "Sachin",
id:1
},
{
name : "Mahendra",
id:2
},
{
name: "Gaurav",
id: 3
},
{
name: "Sidharth",
id: 4
}
]
2)
xxxxxxxxxx
[
{
id:1,
Age: 28,
Gender: 'M'
},
{
id:4,
Age: 29,
Gender: 'M'
},
{
id: 3,
Age: 25,
Gender: 'F'
}
]
Output:
xxxxxxxxxx
[
{
"id": 1,
"Age": 28,
"Gender": "M",
"name": "Sachin"
},
{
"id": 3,
"Age": 25,
"Gender": "F",
"name": "Gaurav"
},
{
"id": 4,
"Age": 29,
"Gender": "M",
"name": "Sidharth"
}
]
Let's talk about the solution now. We are going to achieve this in multiple steps as follows:
Step 1
In step 1, we will store the second input into the input2 variable.
Step 1 Code:
xxxxxxxxxx
%dw 2.0
output application/json
var input2=[
{
"id":1,
"Age": 28,
"Gender": 'M'
},
{
"id":4,
"Age": 29,
"Gender": 'M'
},
{
"id": 3,
"Age": 25,
"Gender": 'F'
}
]
Step 2
In step 2, we will first apply a map to the payload.
After that, we will apply a map on the input2 variable inside our previous map.
After that, we will check to create the desired output if the ID of the payload matches the ID of input2.
If the condition is false then we will use null.
Step 2 Code:
xxxxxxxxxx
%dw 2.0
output application/json
var input2=[
{
"id":1,
"Age": 28,
"Gender": 'M'
},
{
"id":4,
"Age": 29,
"Gender": 'M'
},
{
"id": 3,
"Age": 25,
"Gender": 'F'
}
]
---
payload map ((item, index) -> input2 map ((item1, index1) -> if(item.id == item1.id){
"id": item1.id,
"Age": item1.Age,
"Gender":item1.Gender,
"name": item.name
} else null))
Step 2 Output:
xxxxxxxxxx
[
[
{
"id": 1,
"Age": 28,
"Gender": "M",
"name": "Sachin"
},
null,
null
],
[
null,
null,
null
],
[
null,
null,
{
"id": 3,
"Age": 25,
"Gender": "F",
"name": "Gaurav"
}
],
[
null,
{
"id": 4,
"Age": 29,
"Gender": "M",
"name": "Sidharth"
},
null
]
]
Step 3
In the final step, we are applying flatten to the whole output and using a filter to show records that are not null.
Step 3 Code:
xxxxxxxxxx
%dw 2.0
output application/json
var input2=[
{
"id":1,
"Age": 28,
"Gender": 'M'
},
{
"id":4,
"Age": 29,
"Gender": 'M'
},
{
"id": 3,
"Age": 25,
"Gender": 'F'
}
]
---
flatten(payload map ((item, index) -> input2 map ((item1, index1) -> if(item.id == item1.id){
"id": item1.id,
"Age": item1.Age,
"Gender":item1.Gender,
"name": item.name
} else null))) filter $ != null
Hope this helps improve your DataWeave skills. I am not an expert on DataWeave. I am just sharing what I can solve. Comments are welcome. Thanks.
Opinions expressed by DZone contributors are their own.
Comments