Hi I am trying to loop through a list and accumulate the data by changing the values a bit.
My map is simple : %{"hostname" => "my_host_name", "level" => nil}
Below is the code I am trying with:
msg = Enum.reduce(Map.values(source), [], fn(k, acc) ->
if k do
msg2 = msg2 <> String.replace_suffix(Enum.join(List.wrap(k), " "), "\n", "") <>" "
else
msg2 = msg2 <> "-" <>" "
end
msg2
end)
IO.inspect msg
I am expecting the result : “my_host_name -” in msg object.
Could anyone suggest me a way to achieve it?
Thanks in advance…
I’m totally lost trying to figure out your goal. Why are you just reducing just the values of the map? Why are you concatenating with msg2 inside your if blocks when that has not been defined before? What is going on with the List.wrap and Enum.join and String.replace_suffix?
kokolegorille Thanks for the reply… I am trying loop through a list, use them as keys for fetching values of another map and concatenate the resultant value as string… For example:
list = ["key1,“key2”…] and map={“key1”: “value1”, “key2”: “value2”…}. Json is nested so I need to flatten it out. hence using List.wrap … I would like to get the answer as “value1 value2…”
gregvaughn thanks for the reply. msg2 is the result holder. I am new to Elixir so I might be doing something wrong… But I am trying to loop through the values of the map and do some operation on them and return a new object
Here’s another alternative starting with Map.take/2 and using multiple matching heads in an anonymous function just to show different ways of approaching the problem.
I guess the main difference in how to approach the problem is that you were trying to build up the string in pieces in an Enum.reduce. That can certainly be done, but it’s more “Elixir-ish” to think of transforming lists and in the end combining into a string
EDIT Actually, don’t do what I did above if you care about the order of the values in the string because you can’t trust the ordering of Map.values
I’d kind of be surprised otherwise Your initial code to reduce over the values has the same flaw. That last example from @idi527 is what you should use.