Code Steps - #Vol 1 - Iterating over an array and replacing with an object

code steps zapier Oct 06, 2022
Code Steps # Volume 1

I've decided to begin documenting commonly used code steps and the purpose they serve in Zapier/Airtable. This is because I commonly come up against a few similar problems and because the internet makes it so easy to write JS without having to understand it, I'll often forget how I approached a problem before, only to find that the solution I come up with is the same as my original solution. 

Let's take the below example. Let's say we have emails that we want to CC, but we don't know how many we might get, and we are faced with the following problem:

How to turn a list like the below, of variable size into individual items that we can enter into Zapier

"[email protected], [email protected], [email protected]" etc

 

We can achieve the above by using a code step where the variable entered is "emails"

var emails = inputData.emails;
var primaryEmail;
var ccEmails;
var ccEmailsOut = {};

if (emails.includes(",")) {
  var emailArr = emails.split(",");
  primaryEmail = emailArr[0];
  ccEmails = emailArr.slice(1);
} else {
  primaryEmail = emails;
}

if (ccEmails) {
  for (let i = 0; i < ccEmails.length; i++) {
    ccEmailsOut[`${i}`] = ccEmails[i];
  }
}
output = [{ primaryEmail, ccEmailsOut }];

The most important part of this code step is the following line:

ccEmailsOut[`${i}`] = ccEmails[i];

It allows us to create an array of dynamic objects, which we iterate over, and outputs each item as a unique variable in the JS step's output object, allowing us to simply copy one of the records, and replace with as many as we would like. So you would end up, in the following step bringing through as many emails as you want by changing the value highlighted in red below:

{{168478655__ccEmailsOut__1}}

I hope that helps some of you. I'm really documenting these for myself more than anything, but if I can help you along the way, that's an added bonus. 😊