Nav

To Use For Each over a Collection (Design Center)

If you’re sending data as a collection (a list, an array or a map) through your flow, you can process each element in the collection separately. This is similar to using a For Each statement in most programming languages.

You achieve this by placing components inside a For Each scope. When a Mule message containing a collection flows through a For Each scope, it is split into a series of separate Mule messages. The elements in the scope process these separate Mule messages one at a time. Once the messages have all gone through what’s in the scope, they are merged back as a collection into a single Mule message.

  1. In Design Center add a For Each scope to your flow.

  2. Keep the default settings and close the settings panel.

    Default settings expect the payload to be a collection of elements. Each one of these collection elements is used separately inside the scope.

  3. Within the For Each scope, click on the plus sign and add one or more components.

    for each task design center afce9

    These compoonents receive separate elements of the collection as their input.

Going Over a Nested Collection

If the collection you want to go over is nested in a data structure, you can tell the For Each scope where to find the collection to use. After the scope is done going over each element in the collection, it rebuilds the original data structure it received besides the collection it worked with.

  1. Open a For Each card to edit its properties.

  2. Change the Collection field to point to the collection you want to iterate over.

    For example, in the object below, if you want to go over the collection nested in field3 you must set the Collection field to payload.myobject.field3.

    
                
             
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    {
      "myobject": {
         "field1": "some-value",
         "field2": 42,
         "field3": [
           { "element1": {"a": 1, "b":2}},
           { "element2": {"a": 3, "b":4}},
           { "element3": {"a": 5, "b":6}},
           { "element4": {"a": 7, "b":8}}
         ]
       }
    }