coderz.py

Keep Coding Keep Cheering!

pluck function in DataWeave 2.0 (mulesoft)

The pluck() function in DataWeave 2 is a function used to convert the properties and values of these properties of an object into an array of properties, an array of values and an array of indices of those properties. This is the function to use if you need to transform an Object into an Array.

Syntax:

pluck(Object<K,V>, (V,K,Number) -> T): Array<T>
pluck<K, V, R>(@StreamCapable object: { (K)?: V }, mapper: (value: V, key: K, index: Number) -> R): Array<R>

Here’s an example of using pluck to take in an Object, and create an Array where each element is a single key-value pair from the input object:


Input

{
  "firstName": "Avery",
  "lastName": "Chance",
  "age": 56,
  "occupation": "Physicist"
}

DW Script

%dw 2.0
output json
---
payload pluck (v,k,idx) -> {(k): v}

Output

[
  {"firstName": "Avery"},
  {"lastName": "Chance"},
  {"age": 56},
  {"occupation": "Physicist"}
]

$ will return values, $$ will return keys and $$$ will return indexes.

Source

%dw 2.0
output application/json
var requestBody= 
{
    "name":"Jack",
    "name":"James",
    "name":"Joseph"
}
---
{
value: requestBody pluck $,
keys: requestBody pluck $$,
indexes: requestBody pluck $$$
}

Output

{
  "value": [
    "Jack",
    "James",
    "Joseph"
  ],
  "keys": [
    "name",
    "name",
    "name"
  ],
  "indexes": [
    0,
    1,
    2
  ]
}

Source

%dw 2.0
output application/json
var requestBody= 
{
"car" : 
{
"Make&Model": "Maruti Suzuki Swift",
"MakeYear": 2017,
"Color": "Red",
"Type": "Hatchback",
},
"car" : 
{
"Make&Model": "Maruti WagonR",
"MakeYear": 2018,
"Color": "Brown",
"Type": "Hatchback",
},
"car" : 
{
"Make&Model": "Honda City",
"MakeYear": 2017,
"Color": "Red",
"Type": "Sedan",
},
"car" : 
{
"Make&Model": "Ford Figo",
"MakeYear": 2017,
"Color": "Black",
"Type": "Hatchback",
}
}
---
car:requestBody pluck $ filter $.Color == "Red"

Output

{
  "car": [
    {
      "Make&Model": "Maruti Suzuki Swift",
      "MakeYear": 2017,
      "Color": "Red",
      "Type": "Hatchback"
    },
    {
      "Make&Model": "Honda City",
      "MakeYear": 2017,
      "Color": "Red",
      "Type": "Sedan"
    }
  ]
}

Follow Me

If you like my post please follow me to read my latest post on programming and technology.

Instagram

Facebook

Leave a Comment

Your email address will not be published. Required fields are marked *

Advertisement