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

Recent Posts

Find Intersection of Two Singly Linked Lists

You are given two singly linked lists that intersect at some node. Your task is…

1 month ago

Minimum Cost to Paint Houses with K Colors

A builder plans to construct N houses in a row, where each house can be…

2 months ago

Longest Absolute Path in File System Representation

Find the length of the longest absolute path to a file within the abstracted file…

2 months ago

Efficient Order Log Storage

You manage an e-commerce website and need to keep track of the last N order…

3 months ago

Select a Random Element from a Stream

You are given a stream of elements that is too large to fit into memory.…

3 months ago

Estimate π Using Monte Carlo Method

The formula for the area of a circle is given by πr². Use the Monte…

3 months ago