Search code examples
javascriptzapier

How to properly format working javascript for Code by Zapier


I'm trying to recreate a simple javascript for loop to run in Zapier.

My Javascript skills would likely place me as "experienced but still newbish", so converting this to function correctly in Zapier has proven rather difficult. My code operates as expected until I attempt to rewrite it using Zapier's requirements.

For the example below, I have substituted the inputData with dummy text in "input".

Here's an example of my working model in JS:

const input = "Company Name: Shire Homes, Inc. | First Name: Frodo 
| Last Name: Baggins |"
const fout = input.match(/\: (.*?) \|/g)

for (let i = 0; i < fout.length; i++) {
  console.log(fout[i].slice(2, -2))
}

Which logs:

Shire Homes, Inc. Frodo Baggins

Since Zapier requires the data to be returned, instead of iterating over each string against the regex, I only get the first string and then it stops. How would one rewrite this to function correctly in Zapier?

I need to return each iteration as a string value since I'm going to be inserting the data elsewhere.

Thanks in advance!


Solution

  • Great question!

    Instead of just iterating over the matches, you want to do something with each of them and get the result. The best way to do this is the .map function (docs).

    And like you mentioned, you need to return something from the whole function. There are a few options and which you want depends on what the eventual Zap will do.

    1. If you want the output to be a single string (such as "Shire Homes, Inc.,Frodo,Baggins") to use it all at once, then you'll want to join it.
    2. If you want to use each item separately (such as one step writes "shire" while another writes ("frodo"), you'll return them as an array and the result will fan out. It's unlikely you want this.
    3. If you want to use each separately in subsequent zaps (the most likely option), then you'll want to put it in an object.

    So let's look at the code!

    // this is handled by Zapier already, but we need the variable to test it
    const inputData = {text: "Company Name: Shire Homes, Inc. | First Name: Frodo | Last Name: Baggins |"} 
    const rawSegments = inputData.text.match(/\: (.*?) \|/g)
    
    const segments = rawSegments.map(s => s.slice(2, -2))
    
    // probably want to return an object
    
    // option 1
    // return {result: segments.join('')}
    
    // option 2; probably don't want this
    // return segments
    
    // option 3; probably the best, but depends on the data being in the same order every time
    return {
      company: segments[0],
      fname: segments[1],
      lname: segments[2]
    }
    

    There's some JS shorthand in there, but hopefully it's clear what's going on.