Pass Functions as Arguments

DataWeave 2.1 is compatible with Mule 4.1. Standard Support for Mule 4.1 ended on November 2, 2020, and this version of Mule will reach its End of Life on November 2, 2022, 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.

This DataWeave example defines a base function in the header that receives two arguments: a function and an element to apply it on. The base function the applies the received function onto the keys of the received element and also to every one of its child elements recursively. In this case, the function sent sets all keys to lower case.

The example uses the following:

  • A custom function that is applied recursively, ie: it calls itself for each child in the element it receives originally.

  • mapObject to sort through each child of the element.

  • lower from the Strings library to make every Key in the input lower case.

  • is to check if the passed element is of type Object (and therefore has children).

  • if and else to only have the function call itself when a condition is met, and to otherwise end the recursive loop for that branch.

%dw 2.0
import * from dw::core::Strings
output application/xml
fun applyToKeys(element, func) =
    if (element is Object)
        element mapObject (value, key) -> {
        (func(key)) : applyToKeys( value, func)
    else element
applyToKeys(payload, (key) -> lower(key))
Input XML
    <TITLE>Empire Burlesque</TITLE>
    <ARTIST>Bob Dylan</ARTIST>
    <TITLE>Hide your heart</TITLE>
    <ARTIST>Bonnie Tyler</ARTIST>
Output XML
<?xml version='1.0' encoding='US-ASCII'?>
    <title>Empire Burlesque</title>
    <artist>Bob Dylan</artist>
    <title>Hide your heart</title>
    <artist>Bonnie Tyler</artist>
    <company>CBS Records</company>
Was this article helpful? Thanks for your feedback!
View on GitHub