Please help me to get the below output.
Based on Input1 and Input2 I have get the output. If Id matches then I need to have PATCH method if it does not then I need to have POST method.
If the Id ("ID": "123456") does not exist in input1 then it is POST else it is PATCH.
**Input1: **
{
"prod": [
{
"Id": "123456",
"value": "ABC"
},
{
"Id": "123456",
"value": "DEF"
},
{
"Id": "987654",
"value": "DEF"
}
]
}
Input2:
{
"ProdInfo": {
"Prod": [
{
"Id": "123456",
"value1": "LMN"
},
{
"Id": "123456",
"value1": "OPQ"
},
{
"Id": "654321",
"value1": "OPQ"
}
]
}
}
Output:
{
"output": [
{
"Request": [
{
"method": "PATCH",
"body": {
"ID": "123456",
"Value": "ABC;DEF;LMN;OPQ"
}
},
{
"method": "POST",
"body": {
"ID": "654321",
"Value": "OPQ"
}
}
]
}
]
}
You can approach this problem by grouping by id, then use pluck() to get the key values in a way that can be mapped into the desired output. I added a function to encapsulate some of the inner complexity.
%dw 2.0
output application/json
var input1={
"prod": [
{
"Id": "123456",
"value": "ABC"
},
{
"Id": "123456",
"value": "DEF"
}
]
}.prod groupBy ($.Id)
fun joinValues(v1,v2)=(v1 default [] ++ v2 default []) joinBy ";"
---
{
"output": [
{
Request:
payload.ProdInfo.Prod
groupBy ($.Id)
pluck ((value, key, index) -> {
method: if (namesOf(input1) contains (key as String)) "PATCH" else "POST",
body: {
ID: key,
Value: joinValues(input1[key as String].*value, value.*value1)
}
})
}
]
}
Input payload (equal to input2)
{
"ProdInfo": {
"Prod": [
{
"Id": "123456",
"value1": "LMN"
},
{
"Id": "123456",
"value1": "OPQ"
},
{
"Id": "654321",
"value1": "OPQ"
}
]
}
}
Output:
{
"output": [
{
"Request": [
{
"method": "PATCH",
"body": {
"ID": "123456",
"Value": "ABC;DEF;LMN;OPQ"
}
},
{
"method": "POST",
"body": {
"ID": "654321",
"Value": "OPQ"
}
}
]
}
]
}