Looping through a list of maps

If this list may be long then maybe try to use other methods like bigger database query. If list will not be large then you can do it really simple like:

defmodule Example do
  @details_keys [:amount, :charge, :reference, :req_date, :status, :status_msg]
  @uniq_keys [:entity_name, :image_file, :product_sub_div, :product_sub_div_id]

  def sample(list) when is_list(list) do
    list
    |> Enum.group_by(&Map.take(&1, @uniq_keys), &Map.take(&1, @details_keys))
    |> Enum.map(&Map.put_new(elem(&1, 0), :details, elem(&1, 1)))
  end
end

What we are doing here is simple iteration of full list and grouping it by map of keys which should have same values. Extra third argument allows us to map grouped (by our map as key) values. Here we are simply taking another map, but this time from values which may be different.

In result you will have temporary map with:

  1. keys which stores map of unique values
  2. values which stores a list of details

Second thing is to iterate over such temporary map and simply put every value (list of maps) into a new map key called :details.

Helpful resources:

  1. Enum.group_by/3
  2. Enum.map/2
  3. Map.put_new/3
  4. Map.take/2
  5. elem/2
  6. is_list/1
7 Likes