Sunday, July 6, 2025

Tip #4: Nested loops in n8n

Let's imagine you have some set of data like colors and you want to iterate over all of them. For illustration I will create this data set using Code node:

Creating a data set of colors for outside loop in n8n

And after that I will add a Loop node:

Adding outside loop node in n8n

After executing a workflow we can see 3 items in Done Branch as expected:

Getting color items in Done Branch of outside loop in n8n

Ok, let's now imagine that we have some another data set like integer numbers and we also want to iterate over all of them in a nested loop. I will create another Code node for this:

Creating a data set of integers for nested loop in n8n

And again I will add a nested Loop node:

Adding nested loop node in n8n

And finally let's add Set node to a nested loop to show the current values of color and integer number:

Adding Set node to the nested loop to show the current values of both loops in n8n

The final workflow should look like this:

The final workflow to illustrate nested loops in n8n

Now let's execute the workflow and check the results. What we can see is that outside loop's Done Branch has 18 items and the values are quite odd:

Odd results of using nested loops in n8n

This is not we were expecting though. It looks like nested loops are not supported according to the comment of n8n team. But there is a workaround - let's move the body of outside loop to a separate sub-workflow:

Moving outside loop body to a separate sub-workflow in n8n

It should have "color" input parameter:

Adding color input parameter to a sub-workflow in n8n

And it also requires the change in Set node - we don't have outside loop here but have sub-workflow input instead:

Changing Set node in a nested loop in n8n

Then get back to the main workflow and add Execute Sub-workflow node to call our sub-workflow with a nested loop:

Calling a sub-workflow with a nested loop in n8n

Pass the color from the outside loop as an input parameter of sub-workflow:

Passing color value from the outside loop as an input parameter of a sub-workflow in n8n

It's time to test it. Let's execute the main workflow and check the results:

Checking the results of using nested loops workaround in n8n

This is exactly what we were expecting to see. So for nested loops in n8n it's possible to use sub-workflow workaround.

No comments:

Post a Comment