I am looking for a solution to filter an object in a nested array in data weave. I have found a solution that does the job but it looks very cumbersome.
This is my input array:
var inputMessage = [
{
"name": "ben",
"lastName": "TEST1",
"hobby": [{
id: 1,
name: "football",
isDeleted: false
},
{
id: 2,
name: "hockey",
isDeleted: false
}
]
},
{
"name": "Bart",
"lastName": "TEST2",
"hobby": [{
id: 1,
name: "football",
isDeleted: true
},
{
id: 2,
name: "hockey",
isDeleted: false
}
]
}
]
This is the output:
[
{
"name": "ben",
"lastName": "TEST1",
"hobby": [
{
"id": 1,
"name": "football",
"isDeleted": false
},
{
"id": 2,
"name": "hockey",
"isDeleted": false
}
]
}
]
As you see the person object with "Bart" is completely removed. This is done because one of the hobbies of Bart has an isDeleted: true. So when one of a person's hobbies has an is deleted: true then that person's object must be removed.
This is what I have created myself:
output application/json
---
(input message map ($ map object ((value, key, index) ->
if((key ~= "hobby" and (value reduce ((item, acc = []) -> acc + item.isDeleted ) contains(true))))
{"hobby": "remove"}
else
{(key):value})))
filter $.hobby != "remove"
Anybody has an idea or solution for an easier more gentle way to solve this problem?
Try as below. I hope this helps.
Input:
[
{
"name": "ben",
"lastName": "TEST1",
"hobby": [
{
"id": 1,
"name": "football",
"isDeleted": false
},
{
"id": 2,
"name": "hockey",
"isDeleted": false
}
]
},
{
"name": "Bart",
"lastName": "TEST2",
"hobby": [
{
"id": 1,
"name": "football",
"isDeleted": true
},
{
"id": 2,
"name": "hockey",
"isDeleted": false
}
]
}
]
DataWeave Script1:
%dw 2.0
output application/json
---
payload filter ($.hobby filter $.isDeleted == true) == [] map {
name: $.name,
lastName: $.lastName,
hobby: $.hobby
}
Dataweave Script2:
%dw 2.0
output application/json
---
payload filter ((item, index) -> not ((item.hobby filter $.isDeleted == true) != [])) map {
name: $.name,
lastName: $.lastName,
hobby: $.hobby filter $.isDeleted == false
} filter $.hobby != "remove"
Output:
[
{
"name": "ben",
"lastName": "TEST1",
"hobby": [
{
"id": 1,
"name": "football",
"isDeleted": false
},
{
"id": 2,
"name": "hockey",
"isDeleted": false
}
]
}
]