Question

Javascript Array For Loop with If Condition

  • 28 July 2020
  • 1 reply
  • 49 views

Hi,

I was wondering if anyone has a javascript code example they can share or tips on how to get this array For loop working including an “if” condition. I’ve done a lot of searching with no luck. I have 3 line items coming from a GET request step that I’d like to use a code step to convert to an array, iterate through the array with a for loop and If condition to remove rows of the array where one item in the array contains a specific value, then output/return the filtered array. The code does not return an error but the “if” argument doesn’t work - all rows are returned, and the output is a single object instead of individual objects for each row (to be imported to individual cells in Google Sheets). Any suggestions on what the correct method/syntax is here? Thanks in advance!

Here is my code:

 

output = {}

const newArray = inputData.activityName.split(',') // giving a title to the new fields

newArray.forEach(activityName => output[activityName] = {})

inputData.activityName.split(',').forEach((activityName, i) => {output[newArray[i]].activityName = activityName})
inputData.activityDate.split(',').forEach((activityDate, i) => {output[newArray[i]].activityDate = activityDate})
inputData.activityVerb.split(',').forEach((activityVerb, i ) => {output[newArray[i]].activityVerb = activityVerb})

output = [output];
console.log = [output];

const filteredArray = [];

for (let i = 0; i < output.length; i++) {
    const activity = output[i];
    if (activity["activityVerb"] != 'fv') filteredArray.push(activity);
}

output = [{filteredArray}];

 


1 reply

Userlevel 7
Badge +6

@dpitch This is a tricky one for me since I’m not a javascript expert, however,  I see a couple of problems that I think you could clean up in your code. 

 

You are using const to declare filteredArray and activity. It’s my understanding that constants cannot have their value changed (within a block) see more here. So using Const inside the for loop will be fine because the next time it goes through the loop you redeclare the const and that won’t change. However, using Const for filteredArray is probably what is haunting you. 

 

While you’re at it I also noticed that you declare output as an object {} then later on you redeclare it as an array of that object output = [output] And then still later on you set the output to be an array of an object of the filteredArray. 

 

Hopefully, that gets you pointed in the right direction. 

 

 

 

Reply