Contact Us 1-800-596-4880

Map and Flatten an Array

DataWeave 2.2 is compatible and bundled with Mule 4.2. This version of Mule reached its End of Life on May 2, 2023, when Extended Support ended.

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.

The flatMap function calls map on an input and wraps the results in a call to flatten. Before you begin, note that DataWeave version 2 (%dw 2.0) is for Mule 4 apps. For a Mule 3 app, refer to DataWeave 1.0 (%dw 1.0) examples, within the Mule 3.9 documentation set. For other Mule versions, you can use the Mule Runtime version selector in the table of contents.

The flatMap function is useful for refactoring uses of flatten on the results of a call to map. For example, review the following DataWeave script:

DataWeave script:
%dw 2.0
output application/json
var myData = [{name:1},{name:2},{name:3}]
fun myExternalFunction(data): Array =
    if(data.name == 1)
        []
    else if(data.name == 2)
        [{name: 3}, {name:5}]
    else
        [data]
---
//flatten(myData map ((item, index) -> myExternalFunction(item)))
myData flatMap ((item, index) -> myExternalFunction(item))
----

The header of the script creates a variable myData to define an array of objects, each with the key name. It also defines a function with a set of if-else statements that act on name-value pairs with the key name.

The body of the DataWeave script contains the following expressions, each of which produces the same result:

  • flatten(myData map ((item, index) → myExternalFunction(item)))

  • myData flatMap ((item, index) → myExternalFunction(item))

Whether you use the flatMap expression or explicitly use flatten to wrap the map expression, the following takes place:

  1. The expression maps the items in the input array according to if-else conditions in the function myExternalFunction(), which is defined in the header.

    The mapping produces the following output:

    [
      [
      ],
      [
        { "name": 3 },
        { "name": 5 }
      ],
      [
        { "name": 3 }
      ]
    ]
  2. The expression flattens the mapped results by consolidating the elements from the subarrays into a single array, removing the parent array and eliminating the empty child array.

    Flattening produces the following output:

    [
      {
        "name": 3
      },
      {
        "name": 5
      },
      {
        "name": 3
      }
    ]

See Also