News Ticker

DataWeave: the pluck function

Main points:

  • iterates over each key/value pair of an object
  • retrieves key, value and index from an object
  • input is an object and output is an array

What is the pluck function used for?

The pluck function is used to retrieve the key, value and index from an object and output the result to an array. The code snippets in figures 1, 2 and 3 show the retrieval of the object’s key, value and index using the full reference and the built in default.

{pet: "cat", name: "Ponsonby"} pluck (value, key, index) -> key
or
{pet: "cat", name: "Ponsonby"} pluck $$
OUTPUT: ["pet", "name"]

Figure 1: Use pluck to retrieve the all keys from the input object

{pet: "cat", name: "Ponsonby"} pluck (value, key, index) -> value
or
{pet: "cat", name: "Ponsonby"} pluck $
OUTPUT: ["cat", "Ponsonby"]

Figure 2: Use pluck to retrieve the values of all the values in the input object

{pet: "cat", name : "Ponsonby"} pluck (value, key, index) -> index
or
{pet: "cat", name: "Ponsonby"} pluck $$$
OUTPUT: [0, 1]

Figure 3: Use pluck to retrieve the index of all elements in the input object

How does the pluck function work?

The pluck function iterates over each key/value pair of the input object and extract it’s key, value and index and compiles the result to an array. You can use the full reference to key, value and index or the built in defaults $$, $ and $$$ (respectively).

Figure 4: Identify the key, value and index of the input array
Figure 5: Use the built in defaults to refer key, value and index

Example of a combined use of pluck

Here are two further examples of the use of the pluck function. In figure 6 each key/value pair is extracted into an object and compiles into an array.

payload pluck {
  key: $$,
  value: $,
  index: $$$
}
OUTPUT:
[
{
"key": "pet",
"value": "cat",
"index": 0
},
{
"key": "name",
"value": "Ponsonby",
"index": 1
}
]

Figure 6: Extract all parts of an object

In figure 7 all the keys, values and indices are extracted into separate arrays.

{
keys: payload pluck $$,
values: payload pluck $,
indices: payload pluck $$$
}
OUTPUT:
{
"keys": [ "pet", "name" ],
"values": [ "cat", "Ponsonby" ],
"indices": [ 0, 1 ]
}

Figure 7: Extract all keys, values and indices

DataWeave functions

If you enjoyed this blog you might be interested in the following posts about DataWeave functions.

3 Trackbacks / Pingbacks

  1. Constrast DataWeave and Java mapping operations
  2. DataWeave: the map function
  3. DataWeave: the mapObject function

Leave a Reply

%d bloggers like this: