Contact Us 1-800-596-4880

filterObject

filterObject<K, V>(@StreamCapable value: { (K)?: V }, criteria: (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 myObject = {
    str1 : "String 1",
    str2 : "String 2",
    str3 : null,
    str4 : "String 4",
}
---
myObject filterObject $ != null

Output

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

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

Helper function that enables filterObject to work with a null value.