# Looping over arrays

The ability to loop over arrays of data can be very useful in constructing a response. Some of the arrays typically in a response are:

* the elements of path
* the headers in the request
* an array of query parameters if there are more than one with the same name
* a JSON array extracted from the body of a request

The following block is used to loop over an array. If there are no items then the else block will execute:

* `{{#each}} {{else}} {{/each}}`

The following block is used to return the first item from an array. If there are no items then the else block will execute:

* `{{#first}} {{else}} {{/first}}`

You can use the `@index`, `@key` and `this` keywords to determine the index, key and value of the object under the iterator. You can use `@last` keyword to determine if the current object is the last one in the array.

### Example 1:

```handlebars
{{#each Request.Header}}
	{{@index}} : {{@key}} : {{this}}
{{else}}
	No Request Headers were provided
{{/each}}
```

### Example 2:

Using looping and conditional logic you can build our a JSON (or XML) response:

Given the following request body

```json
{
    "people": [
        {
            "name": "John",
            "surname": "Doe",
            "age": 30
        },
        {
            "name": "Jane",
            "surname": "Lee",
            "age": 29
        }
    ]
}
```

And creating the following simulation body template

```json
{ "ages":
    [
        {{#each (Request.Body 'JSONpath' '$.people') }}
        {{this.age}}
        {{#unless @last}},{{/unless}}
        {{/each}}
    ]
}
```

The result generated from the template and sent back in the body would be this:

```json
{
    "ages": [
        30,
        29
    ]
}
```

Follow a tutorial [here ](https://docs.cloud.hoverfly.io/tutorials/response-templating/tut4#part-4.-iterating-over-request-collections)to learn more about looping
