How to loop through a sObject list in Javascript in Aura Lightning Components?

Updated: Jun 9

We have been working on a project handling large data volumes. Instead of constantly calling the server and running Apex, we decided it made more sense to update/transform the data client-side. To do this with record lists in Javascript is very different than in Apex. In Apex you use a 'for each' loop by merely defining the sObject, the variable name, and then the record list variable you will loop through. In Javascript it requires a few more lines of code.


Below we give an example of how you can code one of these record list loops. Then you can do whatever you want with the individual record or record field of the record while in the loop. In this example, we assume you already have made a server call to Salesforce and returned a list of records, which is stored in an Aura:attribute which we have named 'ReturnedObjectList'.

The key difference here is .length which returns the number of records in the myList variable. We can then apply this in our for loop by only iterating through that number of records. We have our start and end point.


We have also added a check on myList to make sure it actually has records (not null) before executing any logic on it.


EDIT 1: Based on some feedback, we are adding a second option for looping through these sObject records, which is even better.

In this example, we create a variable using const and assign the list of records to it. Then using const element of myList we can iterate through the list just like we'd do in Apex. An example of this code in Apex would look something like this:

Hopefully this helps anyone that is struggling on how to loop through Salesforce records. Happy coding!


To get started with Cloud Pacific, go here to complete a simple form. A Cloud Pacific Account Manager will collaborate with you to clarify your needs and goals, and customize a service package and roadmap that will help your business grow and thrive on Salesforce. Reach out to us here!

3,752 views0 comments