Elixir reduce on list of maps

I have this list of maps

[
  %{
    full_name: "name 1",
    id: 2,
    profile_image_url: "https://firebasestorage.googleapis.com/v0/b/"
  },
  %{
    full_name: "test222", 
    id: 27, 
    profile_image_url: nil
  },
  %{
    full_name: "name 3",
    id: 3,
    profile_image_url: "https://firebasestorage.googleapis.com/v0/b/"
  }
]

Now i have to traverse through this map and check if particular id is blocked or not. Based on that i must add one more field called status to this map. like below

[
  %{
    full_name: "name 1",
    id: 2,
    profile_image_url: "https://firebasestorage.googleapis.com/v0/b/",
    status: "blocked"
  },
  %{
    full_name: "test222", 
    id: 27, 
    profile_image_url: nil,
    status: "blocked"
  },
  %{
    full_name: "name 3",
    id: 3,
    profile_image_url: "https://firebasestorage.googleapis.com/v0/b/",
    status: "okay"
  }
]

I am trying like this


              final_list = list 
                            |> Enum.reduce(%{}, fn x, acc -> 

                                  if( Enum.member?(blocked_users_id, x.id) ) do

                                    Map.put(acc, x, x)
                                    Map.put(acc, :status, "blocked")
                                  else
                                    
                                    Map.put(acc, x, x)
                                    Map.put(acc, :status, "okay")
                                  end

                                end)


              IO.inspect final_list

Can anyone help me to figure out what I am doing wrong and how to achieve this?

You might not get what You think with this… as acc is not mutated

acc
|> Map.put(x, x)
|> Map.put(:status, "blocked")
2 Likes

From your description, reduce seems like an odd choice. You start with a list of maps and want to end with a list of maps, so you really want to use an Enum.map operation.

final_list =
  Enum.map(list, fn x -> 
    if( Enum.member?(blocked_users_id, x.id) ) do
      Map.put(x, :status, "blocked")
    else
      Map.put(x, :status, "okay")
    end
  end)

I would likely write it more like:

final_list =
  Enum.map(list, fn x -> 
    status = if x.id in blocked_users_id, do: "blocked", else: "okay"
    Map.put(x, :status, status)
  end)
4 Likes