When your app receives an array from an API request, you can use the Dropsource math Action as a counter to carry out processing on the values received. This tutorial walks you through the process of doing something with the first n items in an array.
With an API request added to your app and returning an array response (represented as a Data Source in the API tab):
- Add a Page Variable to keep track of the array position as you loop through it, naming it something like counter and choosing Java/Swift integer type.
- Add an Action to the 200 Event (or whichever status code is returning the array) of the request in the API tab. Choose the Set Value Action, and initialize the counter variable to zero.
- Next add the Iterate Through Array Action, selecting the array from the Event Data.
The example in this tutorial use the Google Places text search endpoint you can access from the API demo library.
- In the nested Item Event, add an If Else Action to create a conditional test that checks the current count value. For example, if you want to carry out processing on the first three items returned, check if the counter is less than 3 (the count will start at zero so on the third iteration the value will be 2).
- In the nested True Event, add Actions for whatever processing you want to carry out on the first n items. The example plots markers/pins on a map.
- After the If Else, add a Calculate Math Expression Action to increment the counter variable. Add a variable, selecting the Page Variable you added to the page, and reference it in the Expression by name, adding one to it: count+1.
- Save the new counter value to the Page Variable using a Set Value Action, accessing the new count from the Action Data returned by the math Action. (Select the int output on iOS).
If you want to carry out processing on the last n items in an array, you can make additional use of the math Action, for example to subtract the count from the array length property, and test if the result is less than your chosen n value as above.
As this tutorial demonstrates, you can combine the iteration and math Actions to tailor your app display and behavior to your desired user experience, building dynamic data into the process. For a bonus level of processing, try to replicate the “12 open right now” text display you can see at the top of the page in the screengrab above – it uses a conditional test inside the iterate Action to check a boolean value and increment another counter variable if the value is true (the Places API indicates whether each place is currently open). Your apps can also filter the values in an array and find particular values in it.