MuleSoft DataWeave — Part 2

Mridul Dixit
3 min readApr 7, 2024

--

This blog will help in resolving various “how to” queries related to usecases like map function, write variables inline , perform null check etc

1. How to use Map function to iterate over items in an array and outputs the results into a new array

Here initially the structure is as following.

Input :



{"employees":[
{"name":"Ram", "email":"ram@gmail.com", "age":23},
{"name":"Shyam", "email":"shyam23@gmail.com", "age":28}
]}

Now using map function, we can transform the structure by iterating over the given array and create a new array with new structure, where we can have additional fields like “MoreInfo” included as well

Map function Syntax :

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

items : array to map

mapper : Expression used to act on each item and optionally, each index of that item.

Dataweave

%dw 2.0
output application/json
---
payload.employees map (item, index) ->
{
"Name" : item.name,
"Age" : item.age,
"MoreInfo":
{
"Email Address" : item.email,
"EmployeeIndex": index
}
}

Output

Output structure

 {
"Name": "Ram",
"Age": 23,
"MoreInfo": {
"Email Address": "ram@gmail.com",
"EmployeeIndex": 0
}
}

Here we can see new Output structure which includes Name, Age, MoreInfo fields etc

2. How to use variables inline :

%dw 2.0
output application/json
var firstName = "Mridul"
var lastName = "Dixit"
---
{
FullName : firstName ++ lastName,
FullNameWithSpace : firstName ++ " " ++ lastName,
Name: "Hi This is $(firstName) $(lastName)"

}

3. How to perform Null check

isEmpty() is a dataweave core function that can be used to perform null check In Mule 4 , it returns Boolean response (true or false)

It works on Array,String and Object and gives the result accordingly

  • var arr = [“1”,”2",”3"]

Here array is not empty, hence isEmpty(arr) is false

  • var str = “” //Blank string

Here string is empty, hence isEmpty(str) is true

  • var space = “ “ //space

Here string is space and it is considered as string (not empty), hence isEmpty(space) is false

  • var object = {“name” : “Mridul”, “surname” : “Dixit”}

Here object is not empty, hence isEmpty(object) is false

  • var blankObject = “”

Here object is empty, hence isEmpty(object) is true

4. How to count the length of the string or array

%dw 2.0
output application/json
var firstName = "Mridul"
var lastName = "Dixit"
var arr = [1,5,12]
---
{
count : sizeOf(firstName),
countArray : sizeOf(arr)

}

5. How to find the type of data

%dw 2.0
output application/json
var firstName = "Mridul"
var lastName = "Dixit"
var arr = [1,5,12]
---
{

typeArray : typeOf(arr),
typeName : typeOf(firstName)

}

Explore more on DataWeave : MuleSoft DataWeave — Part 1

Explore more on DataWeave : MuleSoft DataWeave — Part 3

--

--

Mridul Dixit

Mulesoft Developer | Paraglider | Neuroscience Enthusiast | Curious Learner