1
votes

I have a scenario where am trying to remove the null and empty objects from the payload and found the below functions but I came to know that "using" is replaced by "do" . may I know how does it look like:

here is the code

%dw 2.0
fun filterValue(value) = value match {
    case is Object -> filterKeyValuePairs(value)
    case is Array -> $ map filterValue($) filter (not (isEmpty($)))
    else -> value
}
fun filterKeyValuePairs(value) = value mapObject (value, key, index) ->
using (filteredValue = filterValue(value)){
    ((key): filteredValue) if (not isEmpty(filteredValue))
}

---
filterValue(payload)
2
looks like i can even do this way: but would like to see how it will be with do fun filterKeyValuePairs(value) = value mapObject (value, key, index) -> { ((key): filterValue(value)) if (not isEmpty(filterValue(value))) } - Learner

2 Answers

3
votes

Same code with do; do basically gives you header --- body

%dw 2.0
fun filterValue(value) = value match {
    case is Object -> filterKeyValuePairs(value)
    case is Array -> $ map filterValue($) filter (not (isEmpty($)))
    else -> value
}
fun filterKeyValuePairs(value) = value mapObject (value, key, index) -> do {
    var filteredValue = filterValue(value)
    ---
    ((key): filteredValue) if (not isEmpty(filteredValue))
}
---
filterValue(payload)

And if you want to do it without a second function:

%dw 2.0
fun filterValue(value) = value match {
    case is Object -> $ mapObject do {
        var filteredVal = filterValue($)
        ---
        (($$): filteredVal) if (not (isEmpty(filteredVal)))
    }
    case is Array -> $ map filterValue($) filter (not (isEmpty($)))
    else -> value
}
---
filterValue(payload)

You could also consider changing it around a bit to take your filter as a function so you could filter on something other than empty values:

fun filterObjectAndArrays(value, fn: (v: Any) -> Boolean) = value match {
    case is Object -> $ mapObject do {
        var filteredVal = filterObjectAndArrays($, fn)
        ---
        (($$): filteredVal) if (fn(filteredVal))
    }
    case is Array -> $ map filterObjectAndArrays($, fn) filter (fn($))
    else -> value
}
---
//payload filterObjectAndArrays (not isEmpty($))
payload filterObjectAndArrays ($ != "a")
1
votes

Did you try using skipOnNull? It also removes empty objects as well:

Check this out

skipNullOn

Skips null values in the specified data structure. By default, it does not skip the values. Valid values are elements, attributes, or everywhere.

arrays
Ignore and omit null values from JSON output, for example, output application/json skipNullOn="arrays".

objects+ Ignore an object that has a null value. The output contains an empty object ({}) instead of the object with the null value, for example, output application/json skipNullOn="objects".

everywhere
Apply skipNullOn to arrays and objects, for example, output application/json skipNullOn="everywhere"