Access atoms in the list and set values


If I have a list of atoms like this

 [:slug, :title]

How can I assign values to the atoms inside the list like tuples

 [{:slug, "some"}, {:title, "title"}]

It is possible? and also convert it into maps at the end



Where do the values come from? If they are calculated by a function f/1 which takes the key as an argument, you can do it using like this:[:slug, :title], &f/1)

And convertig a list of 2-tuples to a map is easily done with Enum.into/2:

Enum.into([:title: "title", slug: "slug"], %{})

So your goal can be reached by just piping your initial list through those functions:

[:slug, :title]
|> Enum.into(%{})

Or you can even use Enum.into/3 which takes a transform function as its third argument:

Enum.into([:slug, :title], %{}, &f/2}

If though, you do not have a function or at least some kind of source which assigns values to the initial list of keys programmatically you are probably out of luck and your task fails already with implementing f/1


well I figure out way to do it. like this:

    required = [:title, :slug]

    fields = for n <- required, do: {n, "title"}


Oh, yes, of course you can use a for-comprehension, I do prefer though the Enum approach, as it is better pipeable and gives a better overview of the data flow.

for does even allow conversion into a map directly:

for n <- [:title, :slug], into: %{}, do: {n, f.(n)}


There is also and

iex>[1, 2, 3], [:a, :b, :c])
[{1, :a}, {2, :b}, {3, :c}]