iamacube

iamacube

Rename all map keys

Hi! I have a list of maps and I want to rename the keys.

What I have:

[info] entities: [ok: %{"Email Address [Required]" => "fblue@mikasa.com", "First Name [Required]" => "Blue", "Last Name [Required]" => "First"}, ok: %{"Email Address [Required]" => "sred@mikasa.com", "First Name [Required]" => "Red", "Last Name [Required]" => "Second"}, ok: %{"Email Address [Required]" => "tyellow@mikasa.com", "First Name [Required]" => "Yellow", "Last Name [Required]" => "Third"}]

What I want to achieve:

[info] entities: [ok: %{"email" => "fblue@mikasa.com", "first_name" => "Blue", "last_name" => "First"}, ok: %{"email" => "sred@mikasa.com", "first_name" => "Red", "last_name" => "Second"}, ok: %{"email" => "tyellow@mikasa.com", "first_name" => "Yellow", "last_name" => "Third"}]

First Name [Required] to first_name
Last Name [Required] to last_name
Email Address [Required] to email

I am not sure how will I work on the keys with all the white space and the [] brackets.

Marked As Solved

Eiji

Eiji

Here is a complete code:

defmodule Example do
  # First of all we call map on our keyword
  def sample(keyword) when is_list(keyword), do: Enum.map(keyword, &rename/1)

  # When key is ok atom and value is a map call rename function
  defp rename({key = :ok, map}) when is_map(map), do: {key, rename(map)}

  # Rename for maps is using for comprehension changing only key and keeping value as is
  defp rename(map) when is_map(map) do
    for {key, value} <- map, into: %{}, do: {rename(key), value}
  end

  # Rename for binary is removing trailing string and calling rename_key
  defp rename(binary) when is_binary(binary) do
    binary |> String.trim_trailing(" [Required]") |> rename_key()
  end

  # A simple pattern-match in rename_key for a special email case
  defp rename_key("Email Address"), do: "email"

  # rename_key for any other string
  defp rename_key(key) when is_binary(key) do
    key |> String.replace(" ", "") |> Macro.underscore()
  end
end

expected_output = [
  ok: %{
    "email" => "fblue@mikasa.com",
    "first_name" => "Blue",
    "last_name" => "First"
  },
  ok: %{
    "email" => "sred@mikasa.com",
    "first_name" => "Red",
    "last_name" => "Second"
  },
  ok: %{
    "email" => "tyellow@mikasa.com",
    "first_name" => "Yellow",
    "last_name" => "Third"
  }
]

input = [
  ok: %{
    "Email Address [Required]" => "fblue@mikasa.com",
    "First Name [Required]" => "Blue",
    "Last Name [Required]" => "First"
  },
  ok: %{
    "Email Address [Required]" => "sred@mikasa.com",
    "First Name [Required]" => "Red",
    "Last Name [Required]" => "Second"
  },
  ok: %{
    "Email Address [Required]" => "tyellow@mikasa.com",
    "First Name [Required]" => "Yellow",
    "Last Name [Required]" => "Third"
  }
]

result = Example.sample(input)
IO.puts(result == expected_output)
# true

Helpful resources:

  1. Kernel.is_list/1
  2. Kernel.is_map/1
  3. Enum.map/2
  4. Kernel.SpecialForms.for/1
  5. String.replace/4
  6. String.trim_trailing/2
  7. Macro.underscore/1
  8. Patterns and Guards

Also Liked

al2o3cr

al2o3cr

The simplest way to accomplish what you’ve written is to look up replacement keys in a supplied map. For instance:

defmodule KeyRenamer do
  @key_replacements %{
    "First Name [Required]" => "first_name",
    "Last Name [Required]" => "last_name",
    "Email Address [Required]" => "email"
  }

  def rename_keys(map) do
    Map.new(map, fn k, v ->
      new_key = Map.get(@key_replacements, k, k)
      {new_key, v}
    end
  end
end

An alternative approach would be to fix the code that’s generating these keys - for instance, if it’s extracting a value from an HTML label maybe it should be using the input’s name or something instead…

blackham

blackham

I don’t mind being that guy that comments on OLD threads. I ran into a sexy way to rename some keys (or all if you want). I tried googling for it later and couldn’t find it. Google just keep sending me back to this thread. I eventually found the solution in some old code. So, I’m going to dump this solution here so next time I’ll find it faster. (and maybe it will help someone else)

To rename SOME of the keys:

bad_data = %{
  "lat" => 12.43244,
  long: -5.342,
  name: "something",
  age: 91
}

good_data = Map.new(bad_data, fn
  {"lat", lat} -> {"latitude", lat}
  {:long, long} -> {:longitude, long}
  anything -> anything
end)

Results:

%{
:age => 91,
:longitude => -5.342,
:name => "something",
"latitude" => 12.43244
}

I mixed :keys and “keys” in the example to show it works with both.

good_data should now have the keys latitude, longitude, name, age. It might be cool if Hexdoc had a section showing some common uses that aren’t functions, but indexed like functions. Example “rename_key()” Don’t need the function because you can easily do it like (copy and paste example above)

sabiwara

sabiwara

Elixir Core Team

If the keys are known and static, and you don’t need to make this logic reusable, you could also use plain pattern-matching:

  def rename_keys(%{
    "First Name [Required]" => first_name,
    "Last Name [Required]" => last_name,
    "Email Address [Required]" => email
  }) do
    %{first_name: first_name, last_name: last_name, email: email}
  end

Where Next?

Popular in Questions Top

albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New

Other popular topics Top

Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 53690 245
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52341 488
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New

We're in Beta

About us Mission Statement