Enum.map to convert string of numbers to keyword list or map for put_assoc

I am struggling with something embarrassingly basic. I just can’t get my head wrapped around Enum.map. I’m pretty sure it’s the best solution for my problem, but can’t format it correctly.

From my form, I have a list of ID numbers for a many-to-many table. So my params look like this:
%{
“title” => “blah”
“description” => “longer blah”
“resource_types” => [“1”, “2”, “5”]
}

I used get_in( params, “resource_types” ) and that returns my list of IDs:

type_list = [“1”, “2”, “5”]

Now I need to convert that into a list that will be accepted by put_assoc which is either a keyword list or a map list. So I’m trying to use Enum.map but can’t quite get it right. I think I also need to convert those string numbers into integers for put_assoc … but not totally sure about that.

formatted_list_map = Enum.map(type_list, fn x-> {:id => String.to_integer(x)} end)

But that fails. Could an Elixir pro help me with this?

formatted_list_map = Enum.map(type_list, fn x-> {:id, String.to_integer(x)} end)

You are only wrong by an operator

1 Like

I think the problem is that this function’s result is not what you’re looking for / is invalid syntax. The => operator is used in a map like %{"key" => "value"} (notice the % in front of the {..}!).

You’re just trying to create a tuple like {key, value} so just replace the arrow with a simple comma should get you further, i think?

Oh my gosh. I can’t believe I was that close. Thank you to both of you! Do either of you know if I need to convert the string-formatted strings to integers for put_assoc?

At least I don’t, sorry…

But I see you opened up a new thread for that anyways, so I hope somebody can help you out there!

Integer.parse/1