pluck

DataWeave 2.2 is compatible and bundled with Mule 4.2. Standard Support for Mule 4.2 ended on May 2, 2021, and this version of Mule will reach its End of Life on May 2, 2023, when Extended Support ends.

Deployments of new applications to CloudHub that use this version of Mule are no longer allowed. Only in-place updates to applications are permitted.

MuleSoft recommends that you upgrade to the latest version of Mule 4 that is in Standard Support so that your applications run with the latest fixes and security enhancements.

pluck({ (K)?: V }, (value: V, key: K, index: Number) -> R): Array<R>

Useful for 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.

Parameters

Name Description

object

The object to map.

mapper

Expression or selector that provides the key, value, and/or index (optional) used for mapping the specified object into an array.

Example

This example iterates over { "a":"b","c":"d"} using the anonymous mapper function ((value,key,index) → { (index) : { (value):key} }) to invert each key-value pair in the specified object and to return their indices as keys. The mapper uses named parameters to identify the keys, values, and indices of the object. Note that you can write the same expression using anonymous parameters, like this: {"a":"b","c":"d"} pluck { ($$$) : { ($):$$} } Unlike the almost identical example that uses mapObject, pluck returns the output as an array.

Source

%dw 2.0
output application/json
---
{"a":"b","c":"d"} pluck (value,key,index) -> { (index) : { (value):key} }

Output

[ { "0": { "b": "a" } }, { "1": { "d": "c" } } ]

Example

This example uses pluck to iterate over each element within <prices/> and returns arrays of their keys, values, and indices. It uses anonymous parameters to capture them. Note that it uses as Number to convert the values to numbers. Otherwise, they would return as strings.

Source

%dw 2.0
output application/json
var readXml = read("<prices>
    <basic>9.99</basic>
    <premium>53.00</premium>
    <vip>398.99</vip>
    </prices>", "application/xml")
---
"result" : {
  "keys" : readXml.prices pluck($$),
  "values" : readXml.prices pluck($) as Number,
  "indices" : readXml.prices pluck($$$)
}

Output

{
   "result": {
     "keys": [ "basic", "premium", "vip" ],
     "values": [ 9.99, 53, 398.99 ],
     "indices": [ 0, 1, 2 ]
   }
}

pluck(Null, (value: Nothing, key: Nothing, index: Nothing) -> Any): Null

Helper function that allows pluck to work with null values.

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub