Reputation: 2650
my need is to go over a list but extract only the first two elements out of that list.
i wrote the following code
payload.list.*listItem filter ($.type == "supervisor") map {
// other code
}
this worked perfectly fine. Then I modified it to extract the first two elements only like this
payload.list.*listItem filter ($.type == "supervisor") [0 to 1] map {
// other code
}
and it doesnt work anymore. i am getting no error but the other code doesnt work as if the map operator has nothing to go over.
also i need to make it work for a scenario if there is only one element after the filter is applied. how should i change my code to make this work.
Upvotes: 0
Views: 591
Reputation: 1301
You need to add parenthesis to ensure precedence. Also, I'm surprised it worked for you at all. I needed to put "type" in single quotes to get it to work since that is a dataweave keyword. I did this ?($$<2)
instead of [0 to 1]
since I wasn't sure if you were guaranteed to have at least two objects in the output of the filter. If you know, you'll have at least two, leave it the way you had it.
(payload.list.*listItem filter ($.'type' == "supervisor"))[?($$<2)] map (value, index) ->
{
"key":value
}
Here's a link to Dataweave documentation on precedence. It snags a lot of people. Safer just to use parens in most cases.
Upvotes: 1
Reputation: 2835
The range selector must be used directly over an Array so you just need to properly do the selection:
(payload.list.*listItem filter ($.type == "supervisor"))[0 to 1] map {
// other code
}
Upvotes: 3