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.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…