There are time 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 selector ? was introduced. This is applicable for both DataWeave 1.0 and 2.0.

Syntax

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

Items' selector
Items’ selector

Output of such prepared transformation is an array. If DataWeave engine will not find any value matching specified condition, it will return null value.

Transformation

Below I have prepared example array containing two addresses. One of them is a living address and the second one is permanent address. To identify which one is it I use type property.

{
"addresses": [
  {
    "type": "PERM",
    "city": "Warsaw",
    "street": "Jerozolimskie",
    "no": 150,
    "postal": "12-233"
  },
  {
    "type": "LIVI",
    "city": "Warsaw",
    "street": "Asfaltowa",
    "no": 111,
    "postal": "99-233"
  }]
}

After transformation I would like to have property permanent and/or living property filled. In order to do this I need to prepare selector based on type property. DataWeave transformation has been depicted below:

DataWeave items' selector example
DataWeave items’ selector example

As you can see I gain access to array’s item by dollar ($) variable. The reason why type property is within single quotas is that type is a reserved DataWeave keyword. For given example I have used as well match operator to map extracted item without unnecessary repetitions. Else part was necessary as in case address is not provided empty value should be returned.

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 to bit confusing. However after I used it a couple of times I get used to it.

DataWeave – Tip #4
Tagged on:         

Leave a Reply

Your email address will not be published. Required fields are marked *