For Each Loop

For Each loops are the most common type of loop used in building backend projects. It allows you to iterate through each item of a given list and do something.


The simplest example is iterating through the results of a Query all Records function. In the screenshot below, you can see the contents of the My First Table Database table.

Let's say we wanted to make an API endpoint that displays all the names in this table as lowercase WITHOUT changing the actual database values. This means that Winston, Sara and Anita would become winston, sara and anita when the API returns to the front-end. To do this using a foreach loop it would look like the following:

Step 1- Query all records from My First Table to get the list of users. You can see below it is returning the list of users as a variable called users

Step 2- Add a For Each Loop and select users as the list you want to iterate through.

By default, each item in the list is returned as item but for this example we'll change it to user (this is optional) so it's clear we're working with users.

Step 3 - CLICK SAVE and re-open the for each function.

Step 4 - Now that we've defined the list (users) we want to iterate through, we need to specify what we want to do with each user . In this case we want to ensure each name in user is lowercase. We can do this with an Update Variable function.

You can see we started by selecting the user variable for the Existing Variable field, then used dot notation to specify we wanted the name field in the user object. We then specified the same variable in the Value field and used the filter to_lower to take the existing name and make it lowercase.

Step 5 - We make sure the response is returning users and if we've done everything right, we can see the names are all lowercase in our response:

If we actually wanted to save the lowercase values to the database instead of displaying them in the API we would have used the Edit Record Database function in the for loop instead of Update Variable

Last updated