# foreach

The `foreach` statement defines a block of zero or more statements and associates this block with multiple values. The block of statements is executed repeatedly, once for each value.

## Syntax

**`foreach`***`parslet`***`as`***`loop_label`***`{`**

```
`# Zero or more USE script statements go here` 
```

**`}`**

{% hint style="info" %}
The opening `{` may be placed on a line of its own if preferred
{% endhint %}

## Details

The `foreach` statement is used to iterate over the values in an array or object (identified by a [parslet](https://olddocs.exivity.io/3.4.3/data-pipelines/extract/parslets)) within the data in a [named buffer](https://olddocs.exivity.io/3.4.3/data-pipelines/extract/language/buffer).

The loop will execute for as many elements as there are in the array, or for as many members there are in the object. For the purposes of this documentation, the term *child* will be used to refer to a single array element or object member.

If the array or object is empty, then the body of the loop will be skipped and execution will continue at the statement following the closing `}`.

The *loop\_label* can be any string, but must not be the same as any other *loop\_label* values in the same scope (ie: when nesting `foreach` loops, each loop must have a unique label). This label is used to uniquely identify any given loop level when loops are nested.

The `foreach` statement will execute the statements in the body of the loop once for every child. `foreach` loops can be nested, and at each iteration the *loop\_label* can be used to extract values from an array or object in the current child using a [dynamic parslet](https://olddocs.exivity.io/3.4.3/data-pipelines/parslets#dynamic-parslets). See the examples at the end of this article for a sample implementation showing this in action.

As the `foreach` loop iterates over the children, a number of variables are automatically created or updated as follows:

| Variable            | Value                                                                                                                 |
| ------------------- | --------------------------------------------------------------------------------------------------------------------- |
| *loop\_label*.COUNT | The number of times the loop has executed. If the object or array is empty then this variable will have a value of 0. |
| *loop\_label*.NAME  | The name of the current child                                                                                         |
| *loop\_label*.VALUE | The value of the current child                                                                                        |
| *loop\_label*.TYPE  | The type of the current child                                                                                         |

## Examples

### Basic looping

Consider the following JSON in a file called `samples/json/array.json`:

```javascript
{
    "totalCount" : 2,
    "items" : [
        {
            "name" : "Item number one",
            "id" : "12345678"
        },
        {
            "name" : "Item number two",
            "id" : "ABCDEFGH"
        }
    ]
}
```

To generate a list of IDs and names from the *items* array, the following would be used:

```
buffer data = file "samples/json/array.json"

foreach $JSON{data}.[items] as this_item
{
    print Customer ${this_item.COUNT}: $JSON(this_item).[id] $JSON(this_item).[name]
}

discard {data}
```

### Nested looping

To extract values from an array using nested loops:

Given the source JSON in a file called `example.json`, the following USE script:

```
var JSON_dir = "examples\json"
buffer example = FILE "${JSON_dir}\doc.json"

var title = $JSON{example}.[title]

# For every element in the 'items' array ...
foreach $JSON{example}.[items] as this_item
{
    var item_name = $JSON(this_item).[name]

    # For every child of the 'subvalues' object ...
    foreach $JSON(this_item).[subvalues] as this_subvalue
    {
        var sub_name = ${this_subvalue.NAME}
        var sub_value = ${this_subvalue.VALUE}

        # Render an output line
        print ${title} -> Item: ${item_name} -> Subvalue:${sub_name} = ${sub_value} 
    }
}
discard {example}
```

will produce the following output:

```
Example JSON data -> Item: Item number one -> Subvalue:0 = 1
Example JSON data -> Item: Item number one -> Subvalue:10 = 42
Example JSON data -> Item: Item number one -> Subvalue:100 = 73
Example JSON data -> Item: Item number one -> Subvalue:1000 = 100
Example JSON data -> Item: Item number two -> Subvalue:0 = 10
Example JSON data -> Item: Item number two -> Subvalue:10 = 442
Example JSON data -> Item: Item number two -> Subvalue:100 = 783
Example JSON data -> Item: Item number two -> Subvalue:1000 = 1009
```
