DataWeave - Filter (short-cut)

DataWeave - Filter  (short-cut)

filter(Array, (item: T, index: Number) -> Boolean): Array

Filter in dataweave used to return the matching values as per the expression applied. It always iterates over an array and returns the array of elements those satisfies the expression. The expression must return true or false. If there are no matches, the output array will be empty.

Example :-

I will use the below input and filter the users based on their age

Input Payload:-

[
  {
    userId: 1,
    firstName: "Krish",
    lastName: "Lee",
    age: 12
  }, 
  {
    userId: 2,
    firstName: "racks",
    lastName: "jacson",
    age: 26
  }, 
  {
    userId: 3,
    firstName: "denial",
    lastName: "roast",
    age: 18
  }, 
  {
    userId: 4,
    firstName: "devid",
    lastName: "neo",
    age: 20
  }, 
  {
    userId: 5,
    firstName: "jone",
    lastName: "mac",
    age: 21
  }
]

Code :-

  • condition : user age should be greater than 18
%dw 2.0
output application/json
---
payload filter $.age > 18

Ouput:-

[
  {
    "userId": 2,
    "firstName": "racks",
    "lastName": "jacson",
    "age": 26
  },
  {
    "userId": 4,
    "firstName": "devid",
    "lastName": "neo",
    "age": 20
  },
  {
    "userId": 5,
    "firstName": "jone",
    "lastName": "mac",
    "age": 21
  }
]

the above same result we can be achieves by using the filter shortcut

here is the shortcut code

                    payload[?($.age>18)]

output will be the same as above

Thank you for taking out time to read the above post. Hope you found it useful. In case of any questions, feel free to comment below. Also, if you are keen on knowing about a specific topic, happy to explore your recommendations as well.

#mulesoft #dataweave #dw #anypointstudio #mule #muleEsb #filter