Mastering DataWeave’s Map and Reduce Functions: A Comprehensive Guide

In this tutorial, we will solve a DataWeave Interview question. This article will help you practice your DataWeave skills in MuleSoft. Here we have to convert input data to a specific type of Output. Let’s get started.

How the input and output looks like?

Input:
[
    {
        "param_name": "first",
        "param_value": "second"
    },
    {
        "param_name": "third",
        "param_value": "fourth"
    }
]
Output:
{
  "first": "second",
  "third": "fourth"
}
Solution:

Lets talk about the solution now. We are going to achieve this in 2 steps as follows:

Step 1:
%dw 2.0
output application/json
---
payload map ((item, index) -> (item.param_name):item.param_value)

Above code we have applied only the map function which will generate the output as below:

[
  {
    "first": "second"
  },
  {
    "third": "fourth"
  }
]
Step 2:

Step 2 contains the final solution where we have applied the reduce function along with the existing logic of map function:

%dw 2.0
output application/json
---
payload map ((item, index) -> (item.param_name):item.param_value) reduce ((item, accumulator) -> accumulator ++ item)

Which will then generate the final output as below:

{
  "first": "second",
  "third": "fourth"
}

Hope this helps in improving your DataWeave skills. Will keep you posted with these kind of problem statements and how to use certain DW functions to ease the transformation process.