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:
{
"firstName": "Avery",
"lastName": "Chance",
"age": 56,
"occupation": "Physicist"
}
%dw 2.0
output json
---
payload pluck (v,k,idx) -> {(k): v}
[
{"firstName": "Avery"},
{"lastName": "Chance"},
{"age": 56},
{"occupation": "Physicist"}
]
$ will return values, $$ will return keys and $$$ will return indexes.
%dw 2.0
output application/json
var requestBody=
{
"name":"Jack",
"name":"James",
"name":"Joseph"
}
---
{
value: requestBody pluck $,
keys: requestBody pluck $$,
indexes: requestBody pluck $$$
}
{
"value": [
"Jack",
"James",
"Joseph"
],
"keys": [
"name",
"name",
"name"
],
"indexes": [
0,
1,
2
]
}
%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"
{
"car": [
{
"Make&Model": "Maruti Suzuki Swift",
"MakeYear": 2017,
"Color": "Red",
"Type": "Hatchback"
},
{
"Make&Model": "Honda City",
"MakeYear": 2017,
"Color": "Red",
"Type": "Sedan"
}
]
}
If you like my post please follow me to read my latest post on programming and technology.
Find the length of the longest absolute path to a file within the abstracted file…
You manage an e-commerce website and need to keep track of the last N order…
You are given a stream of elements that is too large to fit into memory.…
The formula for the area of a circle is given by πr². Use the Monte…
Given an integer k and a string s, write a function to determine the length…
There is a staircase with N steps, and you can ascend either 1 step or…