I think that this can be done as a library. I’ve contributed to one
https://github.com/byjpr/MapRewire that works pretty well. I’ve got another
library that I need to extract from our source code and release as a
package, but it *could* probably be extended (trivially) to allow key
renames as well as its current function (safe atomization of map keys as
well as case conversion).

-a

On Mon, Aug 17, 2020 at 5:35 PM Jonathan Arnett <jonarnet...@gmail.com>
wrote:

> I often times find myself in situations where I need to rename one or more
> keys in a Map, when for instance, converting from Strings to Atoms:
>
> new_map = %{
>   foo: Map.fetch!(old_map, "foo"),
>   bar: Map.fetch!(old_map, "bar"),
>   ...
> }
>
> or otherwise taking a Map from one part of the system and renaming keys to
> make it work in another part of the system:
>
> new_map = %{
>   user_id: post.author_id,
>   content: post.body,
>   ...
> }
>
> With a Map.rename_key/3 function, we could instead write:
>
> new_map =
>   old_map
>   |> Map.rename_key("foo", :foo)
>   |> Map.rename_key("bar", :bar)
>   ...
>
> or:
>
> new_map =
>   post
>   |> Map.rename_key(:user_id, :author_id)
>   |> Map.rename_key(:body, :content)
>   ...
>
> In the situation that you're performing a bulk update of key names (as
> seems to be implied above), Map.rename_keys/3 makes more sense:
>
> new_map = Map.rename_keys(old_map, %{"foo" => :foo, "bar" => :bar, ...})
>
> or:
>
> new_map = Map.rename_keys(post, %{author_id: :user_id, body: :content,
> ...})
>
> With the Map.rename_key[s]/3 functions, the intent is very explicit, and
> induces less cognitive load to understand.
>
> Renaming Map keys is a situation I run into at least monthly, and I do
> wonder whether the rest of the community has this problem as well so as to
> make it a worthwhile addition.
>
> --
> You received this message because you are subscribed to the Google Groups
> "elixir-lang-core" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to elixir-lang-core+unsubscr...@googlegroups.com.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/elixir-lang-core/70108df1-6c5e-475b-8dbd-b4222e920e0bo%40googlegroups.com
> <https://groups.google.com/d/msgid/elixir-lang-core/70108df1-6c5e-475b-8dbd-b4222e920e0bo%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>


-- 
Austin Ziegler • halosta...@gmail.com • aus...@halostatue.ca
http://www.halostatue.ca/http://twitter.com/halostatue

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/CAJ4ekQvR7uwJ7X4BxJYe4UGUuFYpuV7G5JEh0ESdNQ-skecgcg%40mail.gmail.com.

Reply via email to