Contact Us 1-800-596-4880

Define a Function that Flattens Data in a List

When presented with nested structures of data, you might need to reduce (or "flatten") the data in them to produce a simpler output. Before you begin, note that 2.x versions of DataWeave are used by Mule 4 apps. For DataWeave in Mule 3 apps, refer to DataWeave version 1.2 examples. For other DataWeave versions, you can use the version selector in the DataWeave table of contents.

This DataWeave example flattens the data in the interests and contenttypes arrays with the function that is defined in the header, and it only outputs contenttypes when it is not empty.

The example uses these functions:

  • map to go through a set elements in the input.

  • reduce to flatten the arrays.

  • if to conditionally display a field.

  • splitBy to parse the input.

DataWeave Script:
%dw 2.0
output application/json
fun reduceMapFor(data) = data reduce (($$ splitBy ":")[0] ++ "," ++ ($ splitBy ":")[0])
---
payload.results map() ->
{
  email: $.profile.email,
  name: $.profile.firstName,
  tags: reduceMapFor($.data.interests.tags[0]),
        (contenttypes: reduceMapFor($.data.interests.contenttypes[0])) if(sizeOf($.data.interests.contenttypes[0]) > 0)
}
Input JSON Payload:
{
  "results": [
    {
      "profile": {
        "firstName": "john",
        "lastName": "doe",
        "email": "johndoe@demo.com"
      },
      "data": {
        "interests": [
          {
            "language": "English",
            "tags": [
              "digital-strategy:Digital Strategy",
              "innovation:Innovation"
            ],
            "contenttypes": []
          }
        ]
      }
    },
    {
      "profile": {
        "firstName": "jane",
        "lastName": "doe",
        "email": "janedoe@demo.com"
      },
      "data": {
        "interests": [
          {
            "language": "English",
            "tags": [
              "tax-reform:Tax Reform",
              "retail-health:Retail Health"
            ],
            "contenttypes": [
              "News",
              "Analysis",
              "Case studies",
              "Press releases"
            ]
          }
        ]
      }
    }
  ],
  "objectsCount": 2,
  "totalCount": 2,
  "statusCode": 200,
  "errorCode": 0,
  "statusReason": "OK"
}
Output
[
  {
    "email": "johndoe@demo.com",
    "name": "john",
    "tags": "digital-strategy,innovation"
  },
  {
    "email": "janedoe@demo.com",
    "name": "jane",
    "tags": "tax-reform,retail-health",
    "contenttypes": "News,Analysis,Case studies,Press releases"
  }
]