The filterObject
operator iterates over 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.
Syntax:
filterObject<K, V>(@StreamCapable value: { (K)?: V }, criteria: (value: V, key: K, index: Number) -> Boolean): { (K)?: V }
filterObject(Object<K,V>, ((V,K,Number) -> Boolean)): Object<K,V>
filterObject
takes in an Object and a lambda that returns a Boolean. It then returns an Object with the same types as the input Object.
{
"name": "Jerry Schumann",
"age": 34,
"address": "123 Main Street"
}
%dw 2.0
output json
---
payload filterObject (value, key, index) -> key == "age"
{}
What happened? Well, we’ve hinted at this before.
All Object keys in DataWeave are of type Key
, regardless of how the Object keys are created. The ==
operator tests if two values are equal, and part of that means checking that two values are the same type. This is why key == "age"
returned false for every key-value pair in the input Object, Key == String
is always false. How do you deal with this? There are three ways, you can:
key as String == "age"
.key == "age" as Key
.~=
), instead of the “equal to” operator (==
), as key ~= "age"
The ~=
operator and filterObject
function usually go together. If you’re using filterObject to filter an Object based on a key, make sure you keep the ~=
operator in mind!
{
"name": "Jerry Schumann",
"age": 34,
"address": "123 Main Street"
}
%dw 2.0
output json
---
payload filterObject (value, key, index) -> key~="age"
{
"age": 34
}
%dw 2.0
output application/json
var myObject = {
str1 : "String 1",
str2 : "String 2",
str3 : null,
str4 : "String 4",
}
---
myObject filterObject $ != null
{
"str1": "String 1",
"str2": "String 2",
"str4": "String 4"
}
If you like my post please follow me to read my latest post on programming and technology.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…