Somewhat tricky "For" loop question

I have a list of which elements are maps, all of which have the same key, “a”, such as below.
my_list = [%{a: 1}, %{a: 0}, %{a: 3}]

I want to write codes like below.

  1. if “my_list” is empty, “[]”, render A,
  2. if any element of “my_list” has a tuple of which key is “a” and its value is “0”, render B, and stop/break/escape the loop.
  3. if no element of “my_list” has a tuple of key “a” and value “0”, render A.

It seems quite simple, but I can’t find out the solution.
Thank you for reading.

PS> In addition, A and B are LiveView function components.

I don’t understand where the for loop comes in here - it sounds like you always want exactly one of A or B to be rendered.

My translation of your requirements into code:

if Enum.any?(my_list, fn el -> el[:a] == 0 end) do
  # render B
  # render A

Enum.any? will return false when given [], so cases #1 and #3 are both handled by the else.


Hi, al2o3cr

Thank you for the quite simple and amazing solution.
However, liveview doesn’t seem to support it.

<%=if Enum.any?(my_list, fn el -> el[:a] == 0 end) do %>
  <MyComponent.some_function value={el} />
<% end %>

Error: undefined function el/0

Do you have any idea?

Hey @jejuro you didn’t specify that you needed to pass the found value to the component. You are not binding that element to any variable. You need to do:

<%= if el = Enum.find(my_list, fn el -> el[:a] == 0 end) do %>
  <MyComponent.some_function value={el} />
<% end %>
1 Like

Hi, benwilson512
Glad to see the author of the renowned book here. :grinning:

The elements of “my_list” are structs.

<%= if el = Enum.find(my_list, fn el -> el[:a] == 0 end) do %>
  <MyComponent.some_function value={el} />
<% end %>

And, the error message is like;
MyModule.fetch/2 is undefined (MyModule does not implement the Access behaviour. ...)

How to make the Struct fetchible?

Hey @jejuro thanks for the kind words. As a couple of points of feedback, when you ask questions in the future it’s best if you can do more copying and pasting of your actual code and data, particularly when you are new. Your my_list in the original question is a list of maps, which influenced @al2o3cr’s choice to use the [] syntax. If you are dealing with structs you probably want to just do el.a.

1 Like

Just solved.

I changed “el[:a]” to “el.a”, and it works.

Thank you again. al2o3cr and benwilson512.

I have struggled it one full hour. :grin:

Surely, I will do that afterwards. Thank you.