Iterate over an Array
Exercise
Section titled “Exercise”Given the following input payload:
<?xml version="1.0"?><catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> <book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society.</description> </book></catalog>Write a DataWeave transformation that produces the following output:
[ { "index": 0, "id": "bk101", "title": "XML Developer's Guide", "author": "Gambardella, Matthew" }, { "index": 1, "id": "bk102", "title": "Midnight Rain", "author": "Ralls, Kim" }, { "index": 2, "id": "bk103", "title": "Maeve Ascendant", "author": "Corets, Eva" }]Optional:
- Use a lambda to write the transformation.
- To iterate over a list of elements we use the
map(items: Array<T>, mapper: (item: T, index: Number) -> R)function, which takes an Array of elements and a function in charge of transforming each element. - There are several ways to solve it; the easiest and simplest one is using a lambda. Remember that when using a lambda, to refer to the parameters
received by the function we use
$and$$, which stand for theitemandindexparameters.
Show solution
Using a lambda
%dw 2.0output application/json---payload.catalog.*book map { index: $$, id: $.@id, title: $.title, author: $.author}Using a function
%dw 2.0output application/json
fun transformar(item: Object, index: Number): Object = { index: index, id: item.@id, title: item.title, author: item.author}---map(payload.catalog.*book, transformar)Notes:
- When using a lambda, we refer to the element of the list simply with
$, since it is the first parameter (the item) of themapperthemapfunction expects, just as$$is the second parameter, the one standing for the index. - If you use a function instead, you have to write one with the shape
mapexpects:(item: T, index: Number) -> R. So, since theTransformarfunction takes an item and an index and returns an object, it is valid to use inside the mapping function.
{Code mat;}
Learn MuleSoft: courses, exercises and quizzes. Free, no sign-up.
© 2026 Codebymat