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

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

2 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

1 year ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

1 year ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

1 year ago