Reputation: 157
I'm trying to change the format of a list using enum function.
The original list looks like this
myInitialList =
[
{1,
[
["A3", "Teddy"],
["B3", "[email protected]"],
["C3", "56123456"],
["D3", "spain"]
]},
{2,
[
["A4", "Katrin"],
["B4", "[email protected]"],
["C4", "85002145"],
["D4", "USA"]
]},
{3,
[
["A2", "name"],
["B2", "email"],
["C2", "phone"],
["D2", "country"]
]}
]
and I would like to filter the above list to have the below result
myFinalList =
[
%{
name: "Teddy",
email: "[email protected]",
phone: "56123456",
country: "spain"
},
%{
name: "Katrin",
email: "[email protected]",
phone: "85002145",
country: "USA"
}
]
Does anyone have any idea how I can build the filter function?
This will allow me to easily insert the data in my database. I haven't really tried anything since I'm totally stuck from the beginning
in the code, it should look like
myFinalList = myInitialList |> Enum.filter(.....)
Upvotes: 0
Views: 84
Reputation: 121010
In the first place you need to split your input into names and actual values:
[names | items] = myInitialList |> Enum.reverse()
items
here are in the reverse order, but it’s fine.
Now let’s define mapper:
mapper =
fn {_, lists} -> Enum.map(lists, fn [_, e] -> e end) end
And, finally:
for values <- Enum.reverse(items),
do: Enum.into(Enum.zip(mapper.(names), mapper.(values)), %{})
Upvotes: 0
Reputation: 104
You are looking for the Enum.map/2
function. Yo can get myFinalList
with that format doing this:
myFinalList =
Enum.map(myInitialList, fn
{_index, [[_, name], [_, email], [_, phone], [_, country]]} ->
%{
name: name,
email: email,
phone: phone,
country: country
}
end)
Upvotes: 1