coderz.py

Keep Coding Keep Cheering!

The map Function In DataWeave Mule 4

MAP

The map function is used to transform the data contained in an array. It does this by iterating over the elements in the array and applying a transformation to each element. The result of the transformation is collected together and output as an array of transformed elements.

Iterates over items in an array and outputs the results into a new array.

Here’s the type definition for map:

map<T, R>(@StreamCapable items: Array<T>, mapper: (item: T, index: Number) -> R): Array<R>

map(Array<T>, ((T, Number) -> R)): Array<R>

There are two type variables in this definition, T, and R. T represents the type of items that the input Array contains. R represents the type of items that output Array contains. Since map’s job is to transform every item in an Array, it makes sense that the type of items in the input Array and type of items in the output Array are different. Knowing this, the lambda definition makes sense:

((T, Number) -> R)

The lambda’s job is to take in each item of type T from the input Array, as well as the index of that item, and return a new item that will be used in the output Array.

Input

{
    "employee":[
        {
            "FirstName":"John",
            "LastName":"Smith",
            "Email":"john@gmail.com"
        },
        {
            "FirstName":"Bob",
            "LastName":"Stryf",
            "Email":"bob@gmail.com"
        }
    ],
    "Company":{
        "name":"IBM"
    }
}

DW Script

%dw 2.0
output application/json
---
 
{
    "candidatedetails": payload.employee map((item,index) -> {
        "fname":item.FirstName ++ " " ++ item.LastName
    })
}

Output

{
  "candidatedetails": [
    {
      "fname": "John Smith"
    },
    {
      "fname": "Bob Stryf"
    }
  ]
}

Input

[1,2,3,4,5]

DW Script

%dw 2.0
output json
---
payload map (n, idx) -> n + 1

Output

[2,3,4,5,6]

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement