Question

Zapier JavaScript not working with (for i=0) loops

  • 5 December 2021
  • 2 replies
  • 159 views

Hello, 

 

To cut things short, I am experiecing errors when creating JS for-loops with Zapier Code. I have pasted in some dummydata instead of working with inputData for arguments sake. Whenever I try to run this code, I always get an error that ‘i’ is not defined. 

 

The point is that I am looking for a targetID, given that it matches my originalName. To my understanding there isn’t anything wrong with the code. Perhaps someone could point out what I’m obviously not seeing? Biggest thanks!

 

var originalItemName = 'Banana';
var targetItemIDs = [123, 456, 951, 654, 321, 147];
var targetItemNames = ['Apple', 'Kiwi', 'Pineapple', 'Mango', 'Pear', 'Banana'];

for (i=0; i < targetItemIDs.length; i++) {
if (originalItemName === targetItemNames[i]) {
var newItemName = targetItemNames[i];
var newItemID = targetItemIDs[i];
return {newItemName: newItemName, newItemID: newItemID }
}
}

Here is a screenshot of the result: 

 


This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

2 replies

Update: It works this way for just dummydata. But the moment I use  the inputData I keep getting errors that my output is not defined. 

 

This is the code with dummy data:

var originalItemName = 'Apple';
var targetItemIDs = [123, 456, 951, 654, 321, 147];
var targetItemNames = ['Apple', 'Kiwi', 'Pineapple', 'Mango', 'Pear', 'Hoi hoi'];

var i = 0;
for (i; i < targetItemIDs.length; i++) {
if (originalItemName === targetItemNames[i]) {
var newItemName = targetItemNames[i];
var newItemID = targetItemIDs[i];
return {newItemName: newItemName, newItemID: newItemID }
}
}

The result of it:

 

 

This is the code where i replace the simplest variable with my inputdata:

var originalItemName = JSON.stringify(inputData.originalName);  // This equals 'Hoi hoi'
var targetItemIDs = [123, 456, 951, 654, 321, 147];
var targetItemNames = ['Apple', 'Kiwi', 'Pineapple', 'Mango', 'Pear', 'Hoi hoi'];

var i = 0;
for (i; i < targetItemIDs.length; i++) {
if (originalItemName === targetItemNames[i]) {
var newItemName = targetItemNames[i];
var newItemID = targetItemIDs[i];
return {newItemName: newItemName, newItemID: newItemID }
}
}

This is the error:

 

As soon as I do work with ‘output’ instead of ‘return’, I receive errors like: unexpected ‘{‘. I’m clueless why this code won’t work with variable data.

Userlevel 7
Badge +14

Hi @Jeroen 

Try using a JavaScript validator to check your code: https://beautifytools.com/javascript-validator.php

 

JavaScript for loop reference article: https://www.w3schools.com/js/js_loop_for.asp

 

JavaScrip code help: https://zapier.com/help/create/code-webhooks/use-javascript-code-in-zaps

JavaScript code examples: https://zapier.com/help/create/code-webhooks/javascript-code-examples-in-zaps