Update a map that is outside scope of an iterator

For each key in map_A (we don’t care about the values) get another known map (for example sake: map_B ) which is referenced by the key at map_A (that we are looping) and test whether any of the keys in map_B matches some variable x . If match, update value at key in map_A to "yes" , else "no" .

    x = "something"
    map_A = %{"a" => "no", "b" => "no"}

    for f <- Map.keys(map_A) do
        if(Enum.member?(Map.keys(map_B), x) == true) do
            Map.replace(map_A, f, "yes")
        else
            Map.replace(map_A, f, "no")
        end
     end

The problem is that Map.replace(map_A, f, "yes | no") cannot affect map_A outside of the for iteration. The same would apply for Enum.each/2.

map_A = Enum.reduce(map_A, %{}, fn {k, v}, out ->
if Enum.member?(Map.keys(map_B), x) == true) do
Map.put(out, k, “yes”)
else
Map.put(out, k, “no”)
end
end)

You need to remember that whatever way you do it you need to assign the output of the function to your variable.

This is what I’ve got from the code you provided. I pulled out the calculation of the value, because it wasn’t depending on any of the values in map_A, so there’s no reason to repeat that logic.

x = "something"
map_A = %{"a" => "no", "b" => "no"}
value =
  map_B
  |> Map.keys()
  |> Enum.member?(x)
  |> if(do: "yes", else: "no")
  
Map.new(map_A, fn {key, _} -> {key, value} end)