Remove key value pair from a map dynamically

I have this map stored in a customer variable

 %{
    billing_contact: #Ecto.Association.NotLoaded<association :billing_contact is not loaded>,
    billing_contact_id: 305,
    business_contact: #Ecto.Association.NotLoaded<association :business_contact is not loaded>,
   business_contact_id: nil,
   disabled_message: "",
  end_date: nil,
  id: 6851,
 is_disabled: false,
 name: "test",
 start_date: #DateTime<2018-08-17 12:56:50.498078Z>,
 technical_contact: #Ecto.Association.NotLoaded<association :technical_contact is not loaded>,
 technical_contact_id: nil,
 users: #Ecto.Association.NotLoaded<association :users is not loaded>

}

I want to remove all the key value pairs where value is Ecto.Association.NotLoaded. I want to do it dynamically. So when ever there is a map come in. It automatically remove all thekey value pairs where value is Ecto.Association
I have to send this data to the front end. so need to remove this Ecto.Association.Not loaded key value pairs.

Thanks

You can use @derive together with Poison

https://elixir-lang.org/getting-started/protocols.html#deriving

example:

defmodule PersonOnlyName do
  @derive {Poison.Encoder, only: [:name]}
  defstruct [:name, :age]
end

source: GitHub - devinus/poison: An incredibly fast, pure Elixir JSON library

This means that if you encode the struct PersonOnlyName with Poison it will only contain the name field

1 Like

Maybe something like this:

  customer
  |> Enum.filter(fn
    {_, %Ecto.Association.NotLoaded{}} -> false
    _ -> true
  end)
  |> Map.new()

However, if you are using Phoenix, maybe the way to go is to send the full struct to the view which should return the exactly map you want to reply as json. Maybe this view has a function call basic_user, and another full_user when you want to return the full information.

4 Likes

one quick question

Enum.filter takes a list . But how come its working on a map and outputs a list.

Map implements the enumerable protocol.

3 Likes