How can I skip specific items in a For Each loop?
Simple Solutions to skip items when using a For Each loop.
Sometimes, when working with a For Each loop, you don’t want the process to triggered by the loop to run for all items. This can for example be the case when you are iterating over a set of Ads but need to exclude the operation for a subset.
Here are two different approaches to skip items when using a For Each loop:
Example 1: Using a Filter node before the loop
In this example, we’re passing items through a filter before passing them to the For Each loop. This ensures that only the items we want to process based on the filter are used in further steps.
Example JSON
{"nodes":{"input_any_1":{"type":"input_any","logging_enabled":false,"x":483,"y":334,"inputs":{"any":{"title":"items","description":"The any to input","export_enabled":true,"data":[{"name":"Peter","age":24},{"name":"Saul","age":29},{"name":"Jamal","age":31},{"name":"Sarah","age":34},{"name":"Devin","age":20}]}},"outputs":{"any":{"title":"items","description":"The any to input"}}},"filter_v2_1":{"type":"filter_v2","logging_enabled":false,"x":823,"y":238,"inputs":{"filters":{"export_enabled":true,"data":[{"operator":"\u003e","pointer":"/age","value":24}]}}},"for_each_v2_1":{"type":"for_each_v2","logging_enabled":false,"x":1091,"y":236}},"groups":{},"widgets":{},"edges":["filter_v2_1.filtered:for_each_v2_1.start","filter_v2_1.items:for_each_v2_1.items","input_any_1.any:filter_v2_1.items"]}
Example 2: Using an If node behind the loop
In this example, we pass all items to the For Each loop but then determine if it meets certain criteria by extracting a property and passing it to the If node. If the result is false we simply go to the next item in the For Each loop.
Example JSON
{"nodes":{"for_each_v2_1":{"type":"for_each_v2","logging_enabled":false,"x":1090,"y":236},"extract_1":{"type":"extract","logging_enabled":false,"x":1369,"y":236,"inputs":{"pointer":{"export_enabled":true,"data":"/age"}}},"if_v2_1":{"type":"if_v2","logging_enabled":false,"x":1659,"y":236,"inputs":{"condition":{"export_enabled":true,"data":"greater"},"b":{"export_enabled":true,"data":24}}}},"groups":{},"widgets":{},"edges":["extract_1.data:if_v2_1.a","if_v2_1.false:for_each_v2_1.next","for_each_v2_1.item:extract_1.data","for_each_v2_1.do:extract_1.extract","extract_1.extracted:if_v2_1.evaluate"]}
Last updated on October 12, 2022