filterObject

DataWeave 2.2 is compatible and bundled with Mule 4.2. Standard Support for Mule 4.2 ended on May 2, 2021, and this version of Mule will reach its End of Life on May 2, 2023, when Extended Support ends.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

filterObject({ (K)?: V }, (value: V, key: K, index: Number) -> Boolean): { (K)?: V }

Iterates a list of key-value pairs in an object and applies an expression that returns only matching objects, filtering out the rest from the output.

The expression must return true or false. If the expression returns true for a key, value, or index of an object, the object gets captured in the output. If it returns false for any of them, the object gets filtered out of the output. If there are no matches, the output array will be empty.

Parameters

Name Description

value

The source object to evaluate.

criteria

Boolean expression that selects a value, key, or index of the object.

Example

This example outputs an object if its value equals "apple".

Source

%dw 2.0
output application/json
---
{"a" : "apple", "b" : "banana"} filterObject ((value) -> value == "apple")

Output

{ "a": "apple" }

Example

This example only outputs an object if the key starts with "letter". The DataWeave startsWith function returns true or false. Note that you can use the anonymous parameter for the key to write the expression ((value, key) → key startsWith "letter"): ($$ startsWith "letter")`

Source

%dw 2.0
output application/json
---
{"letter1": "a", "letter2": "b", "id": 1} filterObject ((value, key) -> key startsWith "letter")

Output

{ "letter1": "a", "letter2": "b" }

Example

This example only outputs an object if the index of the object in the array is less than 1, which is always true of the first object. Note that you can use the anonymous parameter for the index to write the expression ((value, key, index) → index < 1): ($$$ < 1)

Source

%dw 2.0
output application/json
---
{ "1": "a", "2": "b", "3": "c"} filterObject ((value, key, index) -> index < 1)

Output

{ "1": "a" }

Example

This example outputs an object that contains only the values that are not null in the input JSON object.

Source

%dw 2.0
output application/json
var o = {
    str1 : "String 1",
    str2 : "String 2",
    str3 : null,
    str4 : "String 4",
}
---
o filterObject $ != null

Output

{
  "str1": "String 1",
  "str2": "String 2",
  "str4": "String 4"
}

filterObject(Null, (value: Nothing, key: Nothing, index: Nothing) -> Boolean): Null

Helper function that allows filterObject to work with null values.

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub