DataWeave: The mapObject Function
The mapObject DataWeave function transform data contained in an object. It iterates over each key/value pair, applies a transformation to each key, and outputs an object.
Join the DZone community and get the full member experience.Join For Free
mapObjecttakes an object as an input and outputs an object
mapObjecttransforms each key/value pair in the object
What Is the mapObject Function Used For?
mapObject function is used to transform the data contained in an object, in the same way that the map function transforms the elements of an array. It does this by iterating over each key/value pair in the object and applying a transformation to each key and value. The result of each transformation is formed into an object.
How Is the Transformation Described?
The transformation that is applied to each key and value is described with a DataWeave script. For example, you can refer to the key, value, and index of the object to be transformed in the DataWeave script and apply a transformation such as the
How Does the mapObject Work?
mapObject function takes two inputs, the object to transform and the transformation script which is presented as a lambda expression. The object is always to the left of the
mapObject function and the lambda expression is always on the right of the
Simple Example of the mapObject Function
In the figures below the
mapObject function iterations over the keys and values of the input object (figure 1), and passes each value and key into the lambda expression on the right of the
mapObject function (figure 2). The lambda expression extracts the key, value, and index of each key/value pair and organises them into a new object.
Figure 1: The input object payload to the mapObject function.
The output of the
mapObject mapping transformation collates the input object's key, value, and index as shown in figure 3.
Figure 3: The output from the mapObject transformation.
Use the Built-in Default Short Cuts
The key, value, and index can be replaced by the built-in shortcuts $$, $ and $$$ respectively. The above example can be sampled as shown in figure 4.
Figure 4: Use the built-in default to shorten the code.
DataWeave functions provide transformation capabilities that can transform arrays and objects. For example, the map DataWeave function transforms each element in an array, it accepts an array as input and a DataWeave expression and outputs an array of transformed elements. Another example is the pluck DataWeave function, which iterates over each key/value pair of an object; retrieves key, value, and index; and outputs an array of transformed elements.
Published at DZone with permission of Alex Theedom, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.