String seperated by comma to individual maps

Lets say i am getting values from query_params like usersId=596f0df3421aa940438e18f5,596f09d7421aa9404336e884,596f0df3421aa940438e18f5,596f09d7421aa9404336e884 . Now i need to get each id’s seperated by comma(,) as individual map and perform some operations for each individual id’s. How can i achieve this??

It looks like String.split can help You.

I’m not sure if I do understand correctly what you want, but to extract a list which does hold each ID you can use String.split/3:

"usersId=" <> idString = "usersId=596f0df3421aa940438e18f5,596f09d7421aa9404336e884,596f0df3421aa940438e18f5,596f09d7421aa9404336e884"
#=> "usersId=596f0df3421aa940438e18f5,596f09d7421aa9404336e884,596f0df3421aa940438e18f5,596f09d7421aa9404336e884"

idList = String.split(idString, ",")
#=> ["596f0df3421aa940438e18f5", "596f09d7421aa9404336e884", "596f0df3421aa940438e18f5", "596f09d7421aa9404336e884"]

Now all ids are coming like userId = 596f0df3421aa940438e18f5,596f09d7421aa9404336e884,596f0df3421aa940438e18f5 . I should get it like

“userId” => 596f0df3421aa940438e18f5
“userId” => 596f09d7421aa9404336e884
“userId” => 596f0df3421aa940438e18f5

I should get each Id’s seperately and store them in a database

Please specify how exactly the output should look like and do it in elixir syntax.

You gave us an example and you wanted the comma separated IDs as individuals. Those individuals are in my example bound to idList.

Your expectation you gave us in your recent post is unclear, since we do not know in what kind of collection you wan’t to store the individual user-IDs. Also it will break, since 596f0df3421aa940438e18f5 is neither a valid elixir number, nor a string nor anything else.

Therefore, if we have a converting function, which I do call like this: convert("usersId=596f0df3421aa940438e18f5,596f09d7421aa9404336e884,596f0df3421aa940438e18f5"), what do you expect it to return in elixir syntax?

1 Like

I’m not sure I understand what you want, but one way to solve it assuming the query_params is a map would maybe be like this

usersIds = query_params["usersId"] |> String.split(",")
for id <- usersIds, do: %{"userId" => id}

=> [%{"userId" => "596f0df3421aa940438e18f5"}
%{"userId" => "596f09d7421aa9404336e884"}
%{"userId" => "596f0df3421aa940438e18f5"}
%{"userId" => "596f09d7421aa9404336e884"}]
1 Like

Thank you soo much :slight_smile: