The map() function in DataWeave is a powerful tool for transforming arrays. It iterates over each element, applies a transformation, and produces a new array with the results. This guide will demonstrate its usage with concise examples.
Syntax:
map((item,index) -> your_mapping) Key Concepts:
- Iteration: Applies the mapping logic to each element in the input array.
- Transformation: Defines how to modify each element using the provided mapping function.
- Output: Returns a new array with the same number of elements as the input, containing the transformed results.
Examples:
1. Transforming Strings:
Input:
["jose", "pedro", "mateo"] DataWeave:
%dw 2.0output application/json---["jose", "pedro", "mateo"] map (value, index) -> { name: value, length: sizeOf(value) }Output:
[ { "name": "jose", "length": 4 }, { "name": "pedro", "length": 5 }, { "name": "mateo", "length": 5 }]2. Transforming Numbers:
Input:
[0, 10, 20, 30, 40]DataWeave:
%dw 2.0output application/json---[0, 10, 20, 30, 40] map (value, index) -> (value * 9/5) + 32Output:
[32, 50, 68, 86, 104]3. Transforming Objects:
Input:
[ { "id": 1, "name": "Laptop", "price": 999.99 }, { "id": 2, "name": "Mouse", "price": 19.99 }, { "id": 3, "name": "Keyboard", "price": 49.99 }]DataWeave:
%dw 2.0output application/csv---payload map { id: $.id, name: $.name, price: $.price }Output:
id,name,price1,Laptop,999.992,Mouse,19.993,Keyboard,49.994. Transforming XML:
Input:
<books> <book category="cooking">...</book> <book category="children">...</book> <book category="web">...</book></books>DataWeave:
%dw 2.0output application/json---payload.books.*book map { category: $.@category, title: $.title, price: $.price as Number }Output:
[
{ "category": "cooking", "title": "...", "price": 30 },
{ "category": "children", "title": "...", "price": 29.99 },
{ "category": "web", "title": "...", "price": 49.99 }
]]]>