Wednesday 28 February 2024

Group the objects based on city in MuleSoft 80

Group the objects based on city in MuleSoft

In MuleSoft 4, you can group objects based on their city using the groupBy function within DataWeave:


%dw 2.0
output application/json

var objects = [
  { id: 1, name: "Alice", city: "New York" },
  { id: 2, name: "Bob", city: "London" },
  { id: 3, name: "Charlie", city: "New York" },
  { id: 4, name: "David", city: "Paris" }

// Grouping by city using groupBy function
var groupedObjects = objects groupBy (item) ->;



  1. DataWeave Version: This example specifies DataWeave version 2.0.

  2. Output Format: Defines the output format as JSON.

  3. Objects: Defines an array named objects containing objects with properties like id, name, and city.

  4. Grouping:

  • The groupBy function takes an array and an expression as input.

  • The expression defines the criteria for grouping. In this case, (item) -> groups objects based on their city property.

  • The function returns a map-like object where the keys are unique values from the grouping expression (cities), and the values are arrays containing objects that belong to the respective group.

  1. Output: The write function displays the grouped objects.

Resulting Output:


  "New York": [
      "id": 1,
      "name": "Alice",
      "city": "New York"
      "id": 3,
      "name": "Charlie",
      "city": "New York"
  "London": [
      "id": 2,
      "name": "Bob",
      "city": "London"
  "Paris": [
      "id": 4,
      "name": "David",
      "city": "Paris"

Additional Notes:

  • You can use other expressions within the groupBy function to group objects based on different criteria.

  • DataWeave offers other functionalities like comprehensions for more concise grouping in specific scenarios.

This example demonstrates how to group objects based on the city property using DataWeave in MuleSoft 4. Remember to adapt the code and data according to your specific object structure and grouping requirements.

No comments:

Post a Comment

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