I have a requirement where I need to filter over an array of objects and check whether the "Id" is same for all the lines. If it is same, then "QTY" in the first line should retain the source value "50" in below example and other lines with same "Id" will have "QTY" as 0. However, if the "Id" is not same in all the lines , then the "qty" should retain the same value coming from source for all the lines.
Input Payload:
[
{
"QTY": 50,
"Id": "1111"
},
{
"QTY": 50,
"Id": "1111"
},
{
"QTY": 50,
"Id": "1111"
}
]
Expected Output:
[
{
"QTY": 50,
},
{
"QTY": 0,
},
{
"QTY": 0,
}
]
if the input comes with different "Id" in all Lines like below
[
{
"QTY": 50,
"Id": "1111"
},
{
"QTY": 50,
"Id": "1133"
},
{
"QTY": 50,
"Id": "1122"
}
]
Then expected outcome should be:
[
{
"QTY": 50,
},
{
"QTY": 50,
},
{
"QTY": 50
}
]
This is a simple mapping to leave only the QTY
attribute, but with a condition to just pass the same value unless there is a unique Id
and the index is not the first item. In that case we replace the value by 0. I wrote a helper function to determine if there is a unique Id
by grouping by Id
and counting the number of grouped keys. If the number is 1 there is a single Id
. I use that for a condition, and if true I check the index in the mapping to set 0s.
%dw 2.0
output application/json
fun singleId(a)=sizeOf(a groupBy $.Id pluck $$) == 1
---
payload map (
QTY: if (singleId(payload)) (if ($$==0) $.QTY else 0)
else $.QTY
)