DataWeave Delight: Using pluck function to transform object to array
Sometimes we get a data structure with keys and values and we want to create an array with data from the data structure. DataWeave gives us the pluck
function to achieve this. The input argument is an object and a lambda and the output must be an array. We use a lambda to define the mapping from our object to elements in the resulting array. The lambda has three arguments: the value for a key, the key itself and the index of the key in the object. We have a handle on all data to pluck the information and transform it to elements in an array.
In the following examples we have object structure with keys book1
and book2
that we want to transform to an array. We use the infix notation of the function so our input object is followed by the pluck
function and lambda:
Source
%dw 2.0
// Object structure has already an array like structure,
// but uses keys (book1, book2) for each book object.
// Using pluck we can turn this object into an array.
var books = {
book1: {
title: "Lord of the rings",
price: 30.0
},
book2: {
title: "Hitch-hiker's guide to the galaxy",
price: 42.0
}
}
output application/json
---
{
// Transform object books to array with object
// containing fields with index, key and book details
booksArray: books pluck ((book, key, index) -> {position: index, key: key} ++ book),
// We can easily find all titles from the object using pluck.
// We cannot use books.*title as books is an object not an array.
// Alternatives to get the same result is to use valuesOf function,
// to get all book objects and then map to get the title:
// * valuesOf(books) map (book) -> book.title
// * valuesOf(books).title
bookTitles: books pluck (book) -> book.title,
// The pluck function also allows the dollar-sign to reference the value.
// $$ is the key and $$$ the index.
bookPrices: books pluck $.price
}
Output
{
"booksArray": [
{
"position": 0,
"key": "book1",
"title": "Lord of the rings",
"price": 30.0
},
{
"position": 1,
"key": "book2",
"title": "Hitch-hiker's guide to the galaxy",
"price": 42.0
}
],
"bookTitles": [
"Lord of the rings",
"Hitch-hiker's guide to the galaxy"
],
"bookPrices": [
30.0,
42.0
]
In the next example we add an if/else
to the lambda:
Source
%dw 2.0
var messages = {
"message0": {
"text": "Hi, mrhaki"
},
"message1": {
"text": "Good evening, Hubert"
},
"message3": {
"text": "Hello, DataWeave"
},
"created_with": "DataWeave 2.4"
}
output application/json
---
messages pluck ((value, key, index) -> if (key ~= "created_with") value else value.text)
Output
[
"Hi, mrhaki",
"Good evening, Hubert",
"Hello, DataWeave",
"DataWeave 2.4"
]
Written with DataWeave 2.4.
DataWeave is a functional language designed by MuleSoft for transforming data structures defined in for example JSON, XML or CSV. |