Help

Save the date! Join us on October 16 for our Product Ops launch event. Register here.

Loop Counter + Changing Record Field

Topic Labels: Scripting extentions
1677 1
cancel
Showing results for 
Search instead for 
Did you mean: 
Nathan_Mcwhorte
4 - Data Explorer
4 - Data Explorer

I am new to the scripting platform and what im trying to create is a button that will trigger a script that does the following things.

  • Look at Table - I got this working

  • Look at View - Got this working

  • Results of all Records - i think i have this working via await view.selectrecordsAsync();

  • Run Loop for ‘X’ number of times. Inside this loop i want to update a specific field (for instance Checking a checkbox)

So basically i want to click the button, it goes to a certain view within a table and updates a field of about 100 records, then it will stop.

1 Reply 1

Welcome to the community, @Nathan_Mcwhorter! :grinning_face_with_big_eyes: It looks like you’re heading in the right direction. To loop through the records that you collected from a specific view, you can use the for...of loop structure. More on that can be seen here:

As for the record update itself, that can be done one of two ways.

  1. Update each record individually using table.updateRecordAsync(). The downside to this method is that it’s slow (you’re waiting for each record to update before moving on to the next).
  2. Update records in batches using table.updateRecordsAsync(). This is a lot faster when large collections need to be updated.

To do option #2, try this:

Before looping through the records, create an empty array to contain all record updates:

let updates = []

While looping through the records using the for...of structure mentioned above1, add changes to the updates array using the push() method:

...
updates.push({
  id: record.id, // The ID of the record to update, which you can get in the loop
  fields: {
    "fieldname": fieldValue // refer to docs to know the value required for your field type
  }
})
...

Once the loop finishes, end the script with this, which will update records in groups of 50 (50 is the max allowed by the updateRecordsAsync() method):

while (updates.length > 0) {
  await table.updateRecordsAsync(updates.slice(0, 50));
  updates = updates.slice(50)
}

1 The for...of structure isn’t the only way to do this, but seeing that you’re just starting out, I thought that I’d keep the example simple for now. Because you’re looping through all records in the view, however, a more efficient process would involve using the .map() method on the original records array. If you want to learn more about that, just holler. :slightly_smiling_face: