What is the idiomatic way of checking if a key on a map has a value? For example if we have:
=> (def seq-of-maps [{:foo 1 :bar "hi"} {:foo 0 :bar "baz"}])
To find out all the maps with :foo == 0, I like:
=> (filter (comp zero? :foo) seq-of-maps)
({:foo 0, :bar "baz"})
But if I want to find all the maps with :bar == "hi", the best that I can think of is:
=> (filter #(= (:bar %) "hi") seq-of-maps)
({:foo 1, :bar "hi"})
which I don't find very readable. Is there a better/more idiomatic way of doing it?
Using containsValue() method The standard solution to check if a value exists in a map is using the containsValue() method, which returns true if the map maps one or more keys to the specified value.
To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.
To check for the existence of a particular key in the map, the standard solution is to use the public member function find() of the ordered or the unordered map container, which returns an iterator to the key-value pair if the specified key is found, or iterator to the end of the container if the specified key is not ...
Idiomatic is subjective, but I'd do
=> (filter (comp #{"hi"} :bar) seq-of-maps)
or what you did.
I personally like refactoring this kind of thing to use a clearly named higher order function:
(def seq-of-maps [{:foo 1 :bar "hi"} {:foo 0 :bar "baz"}])
(defn has-value [key value]
"Returns a predicate that tests whether a map contains a specific value"
(fn [m]
(= value (m key))))
(filter (has-value :bar "hi") seq-of-maps)
=> ({:foo 1, :bar "hi"})
Downside is that it gives you an extra function definition to manage and maintain, but I think the elegance / code readability is worth it. This approach can also be very efficient from a performance perspective if you re-use the predicate many times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With