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.
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 Tableto get the list of users. You can see below it is returning the list of users as a variable called
Step 2- Add a For Each Loop and select
usersas the list you want to iterate through.
By default, each item in the list is returned as
itembut 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
useris lowercase. We can do this with an Update Variable function.
You can see we started by selecting the
uservariable 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
user.namein the Value field and used the filter
to_lowerto take the existing name and make it lowercase.
Step 5 - We make sure the response is returning
usersand if we've done everything right, we can see the names are all lowercase in our response: