---
schema_version: "1"
id: c483643f94b6109128325a33927febe0de002d7e9b0e3822b0a934a628110096
title: For Each (<foreach/>)
collection: mulesoft
version: current
locale: en-us
portal_url: https://docs.salesforce.com/mulesoft/current/en-us/anypoint-code-builder/acb-component-for-each.md
canonical_url: https://docs.mulesoft.com/anypoint-code-builder/acb-component-for-each
source_site: docs.mulesoft.com
content_type: documentation
content_hash: 5d692baa5e9fd5bdafa2a999ca297d8dd090fbe71fdca1e1b1d9738014c77be4
description: MuleSoft Documentation Site
latest: true
---
---
product: Anypoint Code Builder
version: master
---

# For Each (<foreach/>)

> For the full documentation index, see: https://docs.mulesoft.com/llms.txt

Process input in a pattern similar to `for-each` or `for` loop in other programming languages.

## Component XML

This component supports the following XML structure:

```xml
<foreach doc:name="For Each"
  doc:id="119e4859"
  collection="#[payload]"
  counterVariableName="counter"
  batchSize="1"
  rootMessageVariableName="rootMessage" />
```

For Each (`<foreach/>`) attributes are configurable through the UI and XML.

<table><colgroup><col> <col> <col></colgroup><thead><tr><th>Attribute Name</th><th>Attribute XML</th><th>Description</th></tr></thead><tbody><tr><td><p><strong>Foreach</strong> (default)</p></td><td><p><code>doc:name</code></p></td><td><div><div><p>Editable name for the component to display in the canvas.</p></div></div></td></tr><tr><td><p>N/A</p></td><td><p><code>doc:id</code></p></td><td><div><div><p>Automatically generated identifier for the component.</p></div></div></td></tr><tr><td><p><strong>Collection</strong></p></td><td><p><code>collection</code></p></td><td><div><div><p>A DataWeave expression that returns a Java collection, object, array, map, or DOM nodes. For Each automatically splits the collection into elements, such as the highest-level objects in a JSON array of objects. Each element becomes the <code>payload</code> on which a processor within For Each acts. For Each accepts collections of any supported content type, such as <code>application/json</code>, <code>application/java</code>, or <code>application/xml</code>. Defaults to <code>payload</code>.</p></div></div></td></tr><tr><td><p><strong>Batch size</strong></p></td><td><p><code>batchSize</code></p></td><td><div><div><p>Number that the scope uses to partition the collected elements from the input into sub-collections of a specified size. For example, if input to For Each is an array of 199 elements and you set the batch size to 50, the scope produces three arrays of 50 elements each and one array of 49 elements. Defaults to <code>1</code>.</p></div></div></td></tr><tr><td><p><strong>Root message variable name</strong></p></td><td><p><code>rootMessageVariableName</code></p></td><td><div><div><p>Configurable name of the variable that stores the complete, un-split Mule message from the original input to For Each. The message contains the payload and any attributes but does not contain any variables (<code>vars</code>), which are part of the Mule event that contains the Mule message. Within For Each, you can gain access to the value of the payload of the message with <code>vars.rootMessage.payload</code> and to attributes of the message with <code>vars.rootMessage.attributes</code>. For Each consumes this variable, so you can access it only from within the scope. Outside For Each, the variable returns <code>null</code>. Defaults to <code>rootMessage</code>.</p></div></div></td></tr><tr><td><p><strong>Counter variable name</strong></p></td><td><p><code>counterVariableName</code></p></td><td><div><div><p>Name of the variable that assigns a number to each iteration over a given element. The sequence starts with <code>1</code> and proceeds sequentially. Using the default name of this property (<code>counter</code>), you can access this number with <code>vars.counter</code>. For Each consumes this variable, so it is not available and returns <code>null</code> when used outside of the scope. Defaults to <code>counter</code>.</p></div></div></td></tr></tbody></table>

## Examples

The following example collects and splits an array of objects that it receives into separate
objects. Components within the scope select a portion of each object, write a portion of that
selected content into separate files, and log the new `payload` that results within For Each.

Assume that For Each receives its input from a scheduled HTTP request for this
[JSON array of objects](https://jsonplaceholder.typicode.com/users).

```xml
(1)
<foreach doc:name="For Each" collection="#[payload]">
  (2)
  <ee:transform doc:name="Transform Message" >
    <ee:message >
      <ee:set-payload ><![CDATA[%dw 2.0
output application/json
---
payload.company]]></ee:set-payload>
    </ee:message>
  </ee:transform>
  (3)
  <file:write doc:name="Write"
    path='#[(payload.name replace " " with("-") ++ "-") ++ (now() as String {format: "uuuuMMddHHmmss"}) ++ ".json"]'
    config-ref="File_Config" mode="CREATE_NEW"/>
  (4)
  <logger level="INFO" doc:name="Logger" message="#[payload]"/>
</foreach>
```

For Each processes the input array:

<table><tbody><tr><td><i data-value="1"></i><b>1</b></td><td>For Each (<code>&lt;foreach /&gt;</code>) collects the entire input payload and splits it into the ten top-level JSON objects within it, such as this one:<div><div><pre><code data-lang="json">{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "Sincere@april.biz",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}</code></pre></div></div></td></tr><tr><td><i data-value="2"></i><b>2</b></td><td>As For Each iterates over each object, the DataWeave expression (<code>payload.company</code>) in the Transform component (<code>&lt;ee:transform /&gt;</code>) uses DataWeave selectors to extract the value of each <code>"company"</code> key and transform the <code>payload</code> to the value of each of those keys. As in a Mule flow, the next component within For Each receives the transformed payload as its input.</td></tr><tr><td><i data-value="3"></i><b>3</b></td><td>The File Write operation (<code>&lt;file:write /&gt;</code>) uses <code>payload.name</code> within a larger DataWeave expression to select the <code>name</code> of each company from the transformed object. The name of each file follows the pattern specified in the expression, which hyphenates the extracted company name and appends a date-time stamp to make the file name unique. For example, the name of a file for Romaguera-Crona data looks like this:<div><div><pre><code data-lang="log">Romaguera-Crona-20221007113314.json</code></pre></div></div><div><p>By default, the operation also loads the payload received from Transform Message to each file.</p></div></td></tr><tr><td><i data-value="4"></i><b>4</b></td><td>The logs print the following message for the first object from the input array:<div><div><pre><code data-lang="log">{
  "name": "Romaguera-Crona",
  "catchPhrase": "Multi-layered client-server neural-net",
  "bs": "harness real-time e-markets"
}</code></pre></div></div></td></tr></tbody></table>

When processing Mule variables, execution within For Each begins with the values of Mule variables
from the previous execution. New Mule variables or modifications to the values of existing variables
that take place when processing one element are accessible during the processing other elements.
Changes to Mule variables continue to be available outside the For Each scope.

```xml
<set-variable variableName="var1" value="var1-BeforeForEach"/>
<set-variable variableName="var2" value="var2-BeforeForEach"/>
<foreach collection="#[['apple', 'banana', 'orange']]">
    <choice>
        <when expression="#[payload == 'apple']">
            <set-variable variableName="var2" value="var2-newValue"/>
            <set-variable variableName="var3" value="var3-appleVal"/>
        </when>
        <when expression="#[payload == 'banana']">
            <set-variable variableName="var3" value="#[vars.var3 ++ ' bananaVal']"/>
            <!-- var3 will now have value 'var3-appleVal bananaVal'-->
        </when>
        <otherwise>
            <set-variable variableName="var3" value="var3-otherVal"/>
            <set-variable variableName="var4" value="var4-val4"/>
        </otherwise>
    </choice>
    <logger level="INFO" doc:name="Logger After Choice"
            message='#[ [vars.var1, vars.var2, vars.var3, vars.var4] as Array ]'/>
</foreach>
<logger level="INFO" doc:name="Logger After For Each"
         message='#[[vars.var1, vars.var2, vars.var3, vars.var4] as Array]'/>
```

As the Choice router (`<choice />`) executes the processors within each condition, the Logger
(`Logger After Choice`) prints the following variable values:

```log
// Condition: when payload == 'apple'
.LoggerMessageProcessor:
[var1-BeforeForEach, var2-newValue, var3-appleVal, null]

// Condition: when payload == 'banana'
.LoggerMessageProcessor:
[var1-BeforeForEach, var2-newValue, var3-appleVal bananaVal, null]

// Condition: otherwise
.LoggerMessageProcessor:
[var1-BeforeForEach, var2-newValue, var3-otherVal, var4-val4]
```

The last values are propagated outside of For Each. The logger (`Logger After For Each`) prints the
same values as the ones printed after the final choice condition (`otherwise`).

```log
[var1-BeforeForEach, var2-newValue, var3-otherVal, var4-val4]
```

## Error Handling

If one of the elements in a collection throws an exception, For Each stops processing that
collection and invokes the error handler.

## See Also

- [Transform Component](https://docs.mulesoft.com/anypoint-code-builder/acb-component-transform)

- [Mule Event Structure](https://docs.mulesoft.com/mule-runtime/latest/about-mule-event)

- [Mule Message Structure](https://docs.mulesoft.com/mule-runtime/latest/about-mule-message)

- [DataWeave Reference](https://docs.mulesoft.com/dataweave/2.4/dw-functions)
