Using filter selector in DataWeave to easily extract data from array

Last Updated on 03/05/2021 by Patryk Bandurski

There are times when you need to get one particular element from an array, but not based on the index. This item needs to fulfill some requirements like equality and so on. In order to perform that task filter selector ‘?‘ was introduced. This is applicable for both DataWeave 1 and 2.

Filter selector syntax

Below you can find the syntax for selecting an element of an array by condition. This operation accepts an array as an input and returns the array as well. In the square brackets, we specify a condition that the items need to fulfill. First, we use the filter selector ‘?‘ sign and after that in parenthesis we put condition. In order to check something against item property, we can use the $ variable to access the item. If we would like to get the item by isAvailable property we would write something like this: $.isAvailable.

Items' selector
Items’ selector

The output of such prepared transformation is an array. If the DataWeave engine will not find any value matching the specified condition, it will return a null value. More about filter selector you can find in MuleSoft documentation here. It is for DataWeave 1 version, for DataWeave 2 it is not described, but it works the same.

Transformation

Below I have prepared an example array containing two addresses. One of them is a living address and the second one is a permanent address. To identify which one is it I use type property. After transformation, I would like to have property permanent and living property filled. In order to do this, I need to prepare a selector based on type property. DataWeave transformation has been depicted below:

Selecting addresses based on type attribute value
Selecting addresses based on type attribute value

As you can see I gain access to the array’s item by dollar ($) variable. The reason why type property is within single quotas is that type is a reserved DataWeave keyword.

Summary

Selector of items from an array is rarely used but it can save a day. I think that it nicely works with a match operator. At first, I found this syntax a little bit confusing. However, after I used it a couple of times I get used to it.

Using filter selector in DataWeave to easily extract data from array

Leave a Reply

Your email address will not be published.

Scroll to top