Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: Delete a value from a Nested Map

Tags:

elixir

Elixir provides a bunch of helper functions in Kernel that let you get and update values from a nested Map or another struct that implements Access:

  • get_in/2
  • put_in/3
  • update_in/3

But I couldn't find anything that could help me delete a value. I know I could just update the value to nil (or just not be lazy by fetching the nested map, deleting the value and putting the whole map in), but I was hoping for a simple one liner that would actually delete the value that maybe I missed.

like image 905
Sheharyar Avatar asked Mar 22 '26 02:03

Sheharyar


1 Answers

After googling a bit I decided to post this as a feature request in the official elixir mailing list, only to find out that it has already been requested, and an alternative does exist. It's Kernel.pop_in/2, which returns the deleted value and updated map in a tuple:

pop_in(%{user: %{name: "John", age: 27}, [:user, :age])
# => {27, %{user: %{name: "John"}}

José's reasoning for not having a separate delete_in/2 method:

The reason why we choose pop_in/2 is because it provides more features than delete_in on its own and we want to avoid overloading Kernel with too many functions. If your concern is chaining, you can always perform a |> elem(1) after popping.

like image 89
Sheharyar Avatar answered Mar 23 '26 15:03

Sheharyar