Friday 26 April 2024

What is pluck in dataweave?292


In DataWeave, the pluck function is a powerful tool used to transform an object into an array. It iterates over the key-value pairs within the object and allows you to extract specific data based on your requirements.

Here's a breakdown of the pluck function and how it works:


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

Explanation of Arguments:

  • <K, V, R>: These represent the generic types for the object's keys, values, and the return type of the mapper function, respectively.

  • object: This is the input object you want to iterate over.

  • mapper: This is a lambda function that defines how each element (key-value pair) in the object should be processed. It takes three arguments:

  • value: The value associated with the current key in the object.

  • key: The key itself (name of the property) within the object.

  • index: The zero-based index representing the position of the current element within the iteration.

  • Array<R>: The pluck function returns an array containing the results of applying the mapper function to each element in the object.

Extracting Specific Data:

The mapper function provides flexibility in how you extract data from the object:

  • Return Values: You can simply return the value itself to get an array of all object values.

  • Return Keys: To create an array of all object keys (property names), return the key within the mapper.

  • Return Indexes: If you need an array containing the indexes (positions) of each element, return the index.

  • Custom Logic: The mapper allows you to perform more complex transformations on the data. You can combine values, keys, indexes, or use DataWeave expressions to manipulate the data as needed before adding it to the resulting array.


Code snippet

%dw 2.0
output application/json

var myObject = {
  name: "John Doe",
  age: 30,
  city: "New York"

// Extract all values:
var allValues = myObject pluck $;

// Extract all keys (property names):
var allKeys = myObject pluck $$;

// Extract all indexes:
var allIndexes = myObject pluck $$$;

// Combine key and value:
var keyValuePairs = myObject pluck (value, key) -> { key: key, value: value };

write to_string(allValues), write to_string(allKeys), write to_string(allIndexes), write to_string(keyValuePairs);



["John Doe",30,"New York"]
{"key":"name","value":"John Doe"},{"key":"age","value":30},{"key":"city","value":"New York"}

In essence, the pluck function in DataWeave offers a versatile approach to transforming objects into arrays and extracting specific data based on your requirements.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.