Elixir map check if not empty and key exists
Solution 1
Just a small terminology thing, params is a map and not a hash. This is relevant when knowing where to look in the documentation.
For a map there is has_key?/2 which returns true
or false
.
Map.has_key?(params, :name)
Since you are using an Ecto changeset then you can also use Ecto.Changeset.get_change/3.
get_change(changeset, key, default \\ nil)
This returns default
if key
is not set. Please note that if key
is set to nil
then nil
will still be returned. If nil
is a permitted value for your change then you may want to set a different default parameter.
Solution 2
Gazeler's answer is obviously really good. I would only add pattern matching to the mix, as it seems to me, that's the clearest solution, that works not only with phoenix, but with any map anywhere in Elixir.
# head-only declaration for default params
def changeset(model, params \\ :empty)
def changeset(model, %{"username" => _} = params) do
# username field is in params
end
def changeset(model, params) do
# username is not in params
end
Related videos on Youtube
Pratik Khadloya
Updated on July 09, 2022Comments
-
Pratik Khadloya almost 2 years
I am trying to figure out a way to check if the params hash in a Phoenix app (using Elixir) has a particular key or not.
In the below changeset function in a model, the params is defaulted to :empty.
def changeset(model, params \\ :empty) do
I need to figure out if a key named :username exists in the hash.
-
Puzirki about 5 yearsAre you sure is it correct? map = %{"username" => "Name", "ONE_MORE_KEY" => "VALUE"} changeset(map) ----- # username is not in params
-
Jeremy Cochoy over 3 years@Puzirki It may looks conter intuitive at first look but any map with the key "username" will match the pattern
%{"username" => _}
. You can test it in theiex
console by writing%{"username" => val} = %{"x" => 0, "y" => 1, "username" => 10}
.