Translate

Friday 10 November 2023

A dataweave scenariobased question based on distinctBy in Mule Soft

 

A dataweave scenariobased question based on distinctBy in Mule Soft?

Here is a dataweave scenario based question based on distinctBy in MuleSoft:

https://youtu.be/ZFU4rQdBbb8

Scenario:

You have a Mule flow that receives a JSON array of products. The JSON array may contain duplicate products.

Requirement:

You need to use DataWeave to remove the duplicate products from the JSON array and return a new JSON array containing only the distinct products.

Solution:

The following DataWeave code will remove the duplicate products from the JSON array and return a new JSON array containing only the distinct products:

   

Code snippet

%dw 2.0
input = [
  {
    "name": "Product 1",
    "price": 10.00
  },
  {
    "name": "Product 2",
    "price": 20.00
  },
  {
    "name": "Product 1",
    "price": 10.00
  },
  {
    "name": "Product 3",
    "price": 30.00
  }
]

// Remove the duplicate products from the JSON array.
output = input | distinctBy(function(product) product.name)

// Return the new JSON array containing only the distinct products.
output

 

Output:

JSON

[
  {
   
"name": "Product 1",
   
"price": 10.00
  },
  {
   
"name": "Product 2",
   
"price": 20.00
  },
  {
   
"name": "Product 3",
   
"price": 30.00
  }
]


Conclusion

The DataWeave distinctBy function can be used to remove duplicate items from a list or array. The distinctBy function takes a function as an argument, which is used to calculate the unique identifier for each item in the list or array. The distinctBy function then returns a new list or array containing only the items with unique identifiers.

 

No comments:

Post a Comment

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