Reputation: 187
I have the below payload from which I need to extract rows where Error[] != null and all other rows where the Id and Date match the errored row's Id and Date.
[
{
"Id": "123",
"Date": "1/1/2021",
"line": "ABC",
"Error": ["Some Error 1", "Some Error 2"]
},
{
"Id": "123",
"Date": "1/1/2021",
"line": "CDB",
"Error": []
},
{
"Id": "123",
"Date": "2/2/2021",
"line": "ABC",
"Error": []
}
]
From the above array, I need to get rows where
Desired Output here should be :
[
{
"Id": "123",
"Date": "1/1/2021",
"line": "ABC",
"Error": ["Some Error 1", "Some Error 2"]
},
{
"Id": "123",
"Date": "1/1/2021",
"line": "CDB",
"Error": []
}
]
Since the Id and Date of 2nd Object match the first object where Error != null, I need to get all those into one array.
How can I achieve the desired output payload? I am able to filter out rows where Error != null, but how do I get all other rows where the Id and Date match to the errored rows?
Upvotes: 0
Views: 1232
Reputation: 263
Accomplished this with two filters. First filter to find all an array of dates that pertain to errors. find all instances in the original array that have the same date and combine into array:
%dw 2.0
output application/json
var data = [
{
"Id": "123",
"Date": "1/1/2021",
"line": "ABC",
"Error": ["Some Error 1", "Some Error 2"]
},
{
"Id": "123",
"Date": "1/1/2021",
"line": "CDB",
"Error": []
},
{
"Id": "123",
"Date": "2/2/2021",
"line": "ABC",
"Error": []
}
]
---
/*An array of dates that contain Error information with default [] to
* account for instances where no errors are present
*/
(data filter (not isEmpty($.Error))) default []
// Filter the data again to add find all objects with that Date and add to
// an array
reduce ((item, acc=[]) -> acc ++ (data filter (item.Date == $.Date and item.Id == $.Id)))
Upvotes: 3
Reputation: 4303
You could try with this approach.
%dw 2.0
output application/json
---
(payload groupBy ($.Id) mapObject {
($ groupBy ($.Date) mapObject {
($$):$
})
})[0]
Another approach but i don't like concatenating in groupBy
%dw 2.0
output application/json
---
payload filter ($.Error != null) groupBy ($.Id ++ "_" ++ $.Date) mapObject {
($$):$
}
Upvotes: 1