DataWeave Pluck Function: Simplify Your MuleSoft Development

Using pluck Function in Dataweave, one can map an Object into an Array. It iterates over an Object to fetch key, value and indices which results into an Array.

It is similiar to mapObject, the only difference is instead of an object it returns an Array.

Function

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

Parameters

ArgumentsDefaults
Value$$
Key$
Index$$$

Retrive all keys from the input object

Input

{
    "name": "John",
    "email": "john@mule.com"
}

DW Logic

%dw 2.0
output application/json
---

//One can use either of the logic to fetch all the keys from an input object

//payload pluck (value, key, index) -> key

payload pluck $$

Output

[
  "name",
  "email"
]

Retrive all values from the input object

Input

{
    "name": "John",
    "email": "john@mule.com"
}

DW Logic

%dw 2.0
output application/json
---

//One can use either of the logic to fetch all the values from an input object

//payload pluck (value, key, index) -> value

payload pluck $$

Output

[
  "John",
  "john@mule.com"
]

Retrive index of all the elements from the input object

Input

{
    "name": "John",
    "email": "john@mule.com"
}

DW Logic

%dw 2.0
output application/json
---

//One can use either of the logic to fetch index of all the elements from an input object

//payload pluck (value, key, index) -> index

payload pluck $$$

Output

[
  0,
  1
]

Use of Pluck Function

Input

{
    "name": "John",
    "email": "john@mule.com",
    "country": "India"
}

DW Logic

%dw 2.0
output application/json
---
{
    result:
    {
        keys: payload pluck $,
        values: payload pluck $$,
        indices: payload pluck $$$
    }
}

Output

{
  "result": {
    "keys": [
      "John",
      "john@mule.com",
      "India"
    ],
    "values": [
      "name",
      "email",
      "country"
    ],
    "indices": [
      0,
      1,
      2
    ]
  }
}