Iterate Fixed number of loop in Mule 4 using Dataweave

 

In this tutorial we will demonstrate how we can iterate fixed number of loop in mule 4 using dataweave

Below is the input you can see the size of the array is 6 but we need to iterate the list only 3 times on the basis of the total count

Input

{
 "totalcount": 5,
 "employees":
    [
      {
        "name":"Sam",
        "age":34
      },
       {
        "name":"Richard",
        "age":38
      },
      {
        "name":"Harry",
        "age":36
      },
       {
        "name":"Tom",
        "age":40
      },
      {
        "name":"David",
        "age":84
      },
      {
        "name":"Chris",
        "age":52
      }
    ]
}

 

Dataweave

%dw 2.0
output application/json
---
(payload.employees  map (()->{
FirstName: $.name,
age: $.age
})) [ 0 to payload.totalcount -3 ]

Output:

[
  {
    "FirstName": "Sam",
    "age": 34
  },
  {
    "FirstName": "Richard",
    "age": 38
  },
  {
    "FirstName": "Harry",
    "age": 36
  }
]
  
Thank you for taking out time to read the above post. Hope you found it useful. In case of any questions, feel free to comment below. Also, if you are keen on knowing about a specific topic, happy to explore your recommendations as well.
 
For any latest updates or posts on our website, you can follow us on LinkedIn. Look forward to connecting with you there.


Share this:
Subscribe
Notify of
guest
6 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Ahmad Alhamad
Ahmad Alhamad
9 months ago

[0 to payload.totalcount-3] not -1

Last edited 9 months ago by Ahmad Alhamad
Bharath
Bharath
7 months ago

The output is incorrect for this scenario. Please check input, age and score are different and to iterate only top 3, the definition in payload must be ‘-3’ instead of ‘-1’

Gopinadh
Gopinadh
7 months ago
Reply to  admin

Still not correct. Only first object in employees array has ‘age’ remaining are score. Change the input from score to age.

pk t
pk t
25 days ago

payload.employees[0 to 2