I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a loss how to do this without an if statement. I also don’t know if rebinding the same variable is a ‘code smell’
data = %{
requireInteraction: true,
title: title,
icon: icon,
click_action: click_action
}
if body do
data = Map.put(data, :body, body)
end
Note variables defined inside case, cond, fn, if and similar do not leak. If you want to conditionally override an existing variable “data”, you will have to explicitly return the variable. For example:
I just want to add the :body key/value pair into the json blob if the body variable isnt nil. Im’ sending a message, and body is optional, but I can’t send NULL in the json or it literally puts a blank space.
Is there a way that doesnt require creating methods to do it? I suppose I could do that, i feel like my module will get cluttered very fast if i have so many methods to do something like that
damnit it converts it to a list… this gives me so much of a headache. i have never been stuck on such easy stuff in so long, this is by far the hardest coding day in LONG TIME
Ok… I guess skip all my preconceptions and just use the method way. The only problem is it doesnt remove the key it only sets it to NULL (I need to remove the key).
I’m more referring to all the errors for everything I try to do, and weird unexpected things (which is normal of course). Not complaining, just saying… brutal
Yes this comes from Erlang. Enum module always returns List. Of course you can do Enum.into(updated_data, %{}), but this makes no sense if you can directly work on Map instead.
Enum is protocol which Map (of course not only) implements, but this means it would return List in (unified) result unless you would not turn it into Map again.
So no matter if you pass List or Map it would always return List. Also when you are returning Tuple (i.e. {key, value}) and collect results then you got List of Tuple (like [{key, value}]) i.e. Keyword (which needs atom as key for example: [a: 5] is [{:a, 5}] nicely printed) which is just List. It’s why typical Map manipulation returns List.
Not sure how Erlang solves it - not even sure which one is faster or slower, but Erlang way is definitely easier to read for me since we have less code.
The only different thing is Enum.reduce/3 which acc (2nd argument is initial value) could be any term and we work directly on it, so instead return Tuple (again {key, value}) we are returning updated version of acc which does not chances its type unless we decide to do so.