MuleSoft DataWeave Part -3
In this blog, I’d like to walk you through various transformations that can be performed in DataWeave like zip, unzip, flatten etc
Zip :
Merges elements from two arrays into an array of arrays.
Syntax :
zip<T, R>(left: Array<T>, right: Array<R>): Array<Array<T | R>>
left : The array on the left-hand side of the function.
right : The array on the right-hand side of the function.
We have two arrays namely employeeNames and country they belong to. Here the idea is to group the employee with their country in one array, for this we will use zip function
DataWeave syntax
%dw 2.0
output application/json
var employeeNames = ["Mridul", "Piotr", "John"]
var country = ["IN","PL","CA"]
---
{
employeeDetails : zip (employeeNames, country),
// employeeDetails : employeeNames zip country (Both are same)
}
Output
Unzip :
It takes an array of arrays as input and does the opposite of zip function
Syntax :
unzip<T>(items: Array<Array<T>>): Array<Array<T>>
DataWeave Syntax :
%dw 2.0
output application/json
var employeeNames = ["Mridul", "Piotr", "John"]
var country = ["IN","PL","CA"]
---
{
employeeDetails : unzip(zip (employeeNames, country))
}
Output
Example 2 :
Flatten :
Convert the array of arrays into a single array with all values.
Syntax :
flatten<T, Q>(@StreamCapable items: Array<Array<T> | Q>): Array<T | Q>
Dataweave :
%dw 2.0
output application/json
var fruits = [
[
"fruit" : "orange",
"fruit" : "apple"
],
[
"fruit" : "grape",
"fruit" : "kiwi"
]
]
---
{
FruitInfo: flatten (fruits)
}
Output
Explore more on DataWeave : MuleSoft DataWeave — Part 1
Explore more on DataWeave : MuleSoft DataWeave — Part 2