Skip to main content
March 2, 2022
Question

Why fruitless foreach returns N lines ?

  • March 2, 2022
  • 14 replies
  • 0 views

Hi,

I'm trying to test a fruitless foreach, and I'm surprised to see that the result is not just null or empty.
- can you tell me why this code returns 20 null lines please (please see the attached file) ? I was expecting an empty list-

- In this case, how to assert that the result is fruitless ?

a!localVariables(
  /* Get a list of 20 Vehicles */
  local!vehicles: a!flatten(rule!CJT2_GetVehiclesWithFilters(
    id: null
  ).data),
  
  /* The id = 550 does not exist in the Vehicles so we'll not find it */
  local!oneVehicle: a!forEach(
    items: local!vehicles,
    expression: if(tointeger(fv!item.id)=550, 
      fv!item, 
      {}
    )
  ),
  
  local!oneVehicle
)


The object of this post, is not to replace foreach by another function (like index or reject) but to understand how works the foreach.

Regards

14 replies

March 2, 2022

The "flatten" function replies to my 2nd question... I can use it.

richardm900458
March 2, 2022

to reduce it to the core:
{} =-> List of variant with 0 items .
You exuted it 20 times so you get a list of variant with 20 items and each of them are a list of variants with no element.
The moment you have no other element, its ignored and for example a car cdt structure is shown

a!isNullOrEmpty(local!oneVehicle) is still true

This should solve your issue.

local!oneVehicle: a!flatten(
    a!forEach(
      items: local!vehicles,
      expression: if(
        tointeger(fv!item.id)=550, 
        fv!item, 
        {}
      )
    )
  ),
  
 


March 2, 2022

Thank you for reply.
I always use the "magic" flatten function.... but in my case I thouht the latter was used as a workaround.

richardm900458
March 2, 2022

stefan mentioned the general "design" issue with it. usually you have different options to filter way more efficient than with a!foreach. 

stefanhelzle0001
Brainy
March 2, 2022

The nature of foreach() is to return a value for each item. This is exactly the reason why I strongly suggest to not use it for filtering.

richardm900458
March 2, 2022

that is the other topic: Why not using the queryfilter for the id in the query ? its the way better approach to filter.

March 2, 2022

As I have mentionned Richard, I was not expecting to go further in this other topic.

My question was only about the "foreach" aspect (maybe I should provide a static set of data for my example ;-) )