Mule4 DataWeave Exercise: map, reduce, and pluck

Using the DataWeave exercise below, I'll demonstrate how to use the reduce, map, valuesOf, splitBy functions, format, and ++ operator.

Given Input:

JSON
 
[
    {
        "empId": "ex12345",
        "fullName": "Peter parker",
        "street": "Second Ave 46",
        "city": "San Francisco",
        "state": "veniam",
        "postal": "sit",
        "country": "Mexico",
        "dept": "hr",
        "joinedDate": "2021-12-22",
        "miles": 68
    },
    {
        "empId": "ex54321",
        "fullName": "Joseph charles",
        "street": "First Ave 47",
        "city": "Bangalore",
        "state": "Karnataka",
        "postal": "560100",
        "country": "India",
        "dept": "finance",
        "joinedDate": "2021-11-15",
        "miles": 49
    }
]

Desired Output:

JSON
 
[
  {
    "firstName": "Peter",
    "lastName": "parker",
    "AddrWithValuesOf": "San Francisco,veniam,sit,Mexico",
    "AddrWithPluck": "San Francisco,veniam,sit,Mexico",
    "miles": 68.00,
    "DateofJoin": "22-Dec-2021"
  },
  {
    "firstName": "Joseph",
    "lastName": "charles",
    "AddrWithValuesOf": "Bangalore,Karnataka,560100,India",
    "AddrWithPluck": "Bangalore,Karnataka,560100,India",
    "miles": 49.00,
    "DateofJoin": "15-Nov-2021"
  }
]

We can accomplish the desired output by writing the following DataWeave.

Dataweave 2: Objects and Arrays

Anybody dealing with Dataweave scripts will often come across situations where an Object needs to be converted into an Array or vice-versa. The Dataweave 2 examples below describe how to convert between Objects and Arrays.

Example 1: Converting an Object to an Array

This example uses the core Dataweave function pluck; it is useful in mapping an object into an array, pluck iterates over an object and returns an array of keys, values, or indices from the object. It is an alternative to mapObject, which is similar but returns an object, instead of an array.