Find a single item in an array, output corresponding field

  • 5 May 2022
  • 0 replies
  • 113 views
Find a single item in an array, output corresponding field
Userlevel 7
Badge +10

Last week I was trying to do something using a Webhooks by Zapier step, but was hitting a wall. I was building an app with Adalo and taking advantage of their API to retrieve “author” records from a database.

I wanted to look within those records and match it against a Twitter username from my trigger step, then output the record ID that Adalo would need in order for me to connect that person to an “essay” record.

Overview

In other words:

  • Get Twitter username from trigger
  • Retrieve all the authors from Adalo
  • Find the record that has the username
  • Output the record ID 
  • Use that ID when I create the “essay” record, to link it to an existing author

What I Wanted

If I was getting the name “Joe” from my trigger, I wanted to get the ID of “1” so that I could then use it.

Using Paths + Code Step

I wanted 2 paths:

  1. When an author exists, I want the ID so I can use it in my Create ‘Essay’ Record step
  2. When an author does not exist, I want to first create it and then use that in my Create ‘Essay’ Record step 

The Paths

 

In Path A, this is what the rule looks like. I first make sure that the Records[]name field includes the thing I’m looking for. That part is easy enough.

The Code Step

Once I’ve established that the records do, in fact, contain the one I need then it’s time for the code step.

HUGE thanks to my teammate Alexis Grant, who helped me crack this particular bit of code :)

Here’s what the Code by Zapier step looks like:

 

Under the Input Data section we add the username that we get from the trigger, the names we get from our Webhook step (from Adalo) and also the IDs we get from Adalo.

The code is saying:

  • Those names, split them up so we can get them separately
  • Those IDs, do the same thing
  • Check each of those names and try to find the username
  • When you do, output its ID 

Copy The Code

Replace the words “names”, “ids” and “username” to suit your own use case.

const names = inputData.names.split(",");

const ids = inputData.ids.split(",");

const index = names.findIndex(name => name.includes(inputData.username));

output = {id: ids[index]};

The Takeaway 

Whenever you’re using something like a webhooks step to return all of the records from an API, and you want to find a single one by using a piece of information that you’ve got from an earlier step, this code (or something very similar) should do the trick.

Hope this helps!

 

Possible search terms (because this is a weird one to phrase concisely)

Extract item from array, find single array item, find a single record from GET request


0 replies

Be the first to reply!

Reply