pluck

DataWeave 2.1 is compatible with Mule 4.1. Standard Support for Mule 4.1 ended on November 2, 2020, and this version of Mule will reach its End of Life on November 2, 2022, 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 list (array), pluck iterates over an object and returns an array of keys, values, or indices in that 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

The key, value, and/or index (optional) used for mapping the input object.

Example

This example uses pluck to iterate over each element (object) within <prices/> and returns arrays of their keys, values, and indices.

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($),
  "indices" : readXml.prices pluck($$$)
}

Output

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

Example

You can also use named keys and values as parameters. For example, the next transformation example iterates over the prices input above and outputs an array with a single element. Note that payload pluck(payload.prices) produces the same result as payload pluck(payload[0]).

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")
---
payload pluck(readXml.prices)

Output

[
  {
    "basic": "9.99",
    "premium": "53.00",
    "vip": "398.99"
  }
]

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