9mm

9mm

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

Showing Posts 1 to 10

9mm

9mm OP

It also warns me of this. So confusing :s

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:

MrDoops

MrDoops

So you want to update the body key value pair to the data map when the body key exists?

9mm

9mm OP

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.

MrDoops

MrDoops

You can use Map.has_key?(data, :body) with a case statement. A more Elixir way might be to pattern match on the presence or absence of the map.

def process(%{body: _} = data), do: data
def process(%{} = data), do: %{data | body: nil}
9mm

9mm OP

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

How would the case statement look?

9mm

9mm OP

This has got to be the most frustrating day coding since i learned ruby like 10 years ago JESUS CHRIST.

I have spent 3 hours just trying to get a stupid map to update

Here is what i had so far

data =
  Enum.reject(
    %{
      requireInteraction: true,
      title: title,
      body: body,
      icon: icon,
      click_action: click_action
    },
    &(!elem(&1, 1))
  )
9mm

9mm OP

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

WolfDan

WolfDan

Imo this is a elixir way as well to do it:

data = %{
  requireInteraction: true,
  title: title,
  icon: icon,
  click_action: click_action
}

data =
    if body do
      Map.put(data, :body, body)
    else
      data
    end

personally I’d prefer to create more functions like MrDoops pointed out, you can do anonymous functions as well

9mm

9mm OP

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).

Eiji

Eiji

I don’t like to have two variables with same name in scope. For me such code is less readable.

If you have only one variable like that then use if or && with || instead like:

data = %{…}
updated_data = if body, do: Map.put(data, :body, body), else: data
# or
updated_data = body && Map.put(data, :body, body) || data

In case you need to do it multiple times then I recommend to do something like:

data = %{…}
data2 = %{example: 5, body: body, sample: 10}
Enum.reduce(data2, data, fn {key, value}, acc -> value && Map.put(acc, key, value) || acc)

This is equivalent for maps:

:maps.filter(fn _key, value -> not is_nil(value) end, data)

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews