Search code examples
dataweavemulesoft

Mulesoft Dataweave filter not working on reduce


I am trying to filter out empty or null objects from an array. And after filtering I add all the values of the objects in the array to a single string separated with a whitespace by using a reduce function.

The strange thing is that it looks like the filter function is not working in dataweave playground.

This is my code:


var va = [{
            message: "hallo"
        },
        {
            message: "Error on Employee Number "
        },
        {
            
        }
        ]

var filterOutEmptyValues = va filter ($ != null and $.message != null)

output application/json
---
//filterOutEmptyValues
[{"message" : trim(( filterOutEmptyValues reduce ((item, acc = "") -> acc ++ (item.message ++ " "))))}] 

This code gives an error when the last element is not empty with key "message" then there is no error.


Solution

  • The online dataweave is not that reliable and can sometime behave differently then the actual Runtime. Your code will probably work in with the actual Mule Runtime

    From the error it looks like it has to do something with type inference. Based on the accumulator's type (which is a string) the online playground seems to expect that your item should also be a string. I tried enforcing the type in the reduce parameter, it started to be work reduce ((item: Object, acc = "") -> .

    However, as I mentioned earlier, in the real runtime it should still work.

    Having said that your code can be improved a lot by adding some in built functions so I would like to suggest the below equivalent dataweave

    [
      {
        "message": va.message 
                    filter !isEmpty($)
                    map trim($) // If your messages can contain trailing and leading spaces
                    joinBy " "
    
      }
    ]