I have a Clojure map that may contain values that are nil and I'm trying to write a function to remove them, without much success (I'm new to this).
E.g.:
(def record {:a 1 :b 2 :c nil})
(merge (for [[k v] record :when (not (nil? v))] {k v}))
This results in a sequence of maps, which isn't what I expected from merge:
({:a 1} {:b 2})
I would like to have:
{:a 1, :b 2}
your for list comprehension returns a LIST of maps, so you need to APPLY this list to the merge function as optional arguments:
More concise solution by filtering the map as a sequence and conjoining into a map:
Dont remove false values:
Using dissoc to allow persistent data sharing instead of creating a whole new map:
A variation on @Eelco's answer:
To @broma0's point, it elides any empty maps.
reduce-kv can also be used to remove the keys
You could squish it into a map:
Though Jürgen's (filter second record) approach gets my vote for Niftiest Clojure Trick, I thought I'd toss another way out there, this time using
select-keys
:You can use reduce.
If for some reason you want to keep the ordering (which is usually not important in a map), you can use
dissoc
.