Dataweave 2: Objects and Arrays
In this article, we describe, discuss, and walk through two different Dataweave 2 approaches (pluck and reduce) to convert between Objects and Arrays.
Join the DZone community and get the full member experience.
Join For FreeAnybody dealing with Dataweave scripts will often come across situations where an Object needs to be converted into an Array or vice-versa. The Dataweave 2 examples below describe how to convert between Objects and Arrays.
Example 1: Converting an Object to an Array
This example uses the core Dataweave function pluck; it is useful in mapping an object into an array, pluck iterates over an object and returns an array of keys, values, or indices from the object. It is an alternative to mapObject
, which is similar but returns an object, instead of an array.
Ref: https://docs.mulesoft.com/mule-runtime/4.3/dw-core-functions-pluck
Input:
{
"key1" : "value1",
"key2" : "value2",
"key3" : "value3"
}
Dataweave:
%dw 2.0
output application/json
---
payload pluck ((value, key, index) ->
{
"key" : key,
"value" : value,
"index" : index
}
)
Output:
[
{
"key": "key1",
"value": "value1",
"index": 0
},
{
"key": "key2",
"value": "value2",
"index": 1
},
{
"key": "key3",
"value": "value3",
"index": 2
}
]
Example 2: Converting an Array to an Object
This example uses the core Dataweave function reduce; it is useful in applying a reduction expression to the elements in an array. For each element of the input array, in order to, reduce applies the reduction lambda expression (function), then replace the accumulator with the new result. The lambda expression can use both the current input array element and the current accumulator value.
Ref: https://docs.mulesoft.com/mule-runtime/4.3/dw-core-functions-reduce
Input:
[
{
"key1": "value1"
},
{
"key2": "value2"
},
{
"key3": "value3"
}
]
Dataweave:
%dw 2.0
output application/json
---
payload reduce ($ ++ $$)
Output:
{
"key3": "value3",
"key2": "value2",
"key1": "value1"
}
Hope this helps!
Opinions expressed by DZone contributors are their own.
Comments