What is the best way to filter nil
values from a Clojure map {}
?
{ :a :x :b nil :c :z }
;;=> { :a :x, :c :z }
The nicest way of doing this is actually(into {} (keep second {:a :x :b nil}))
Probably not the best solution, but here's one that uses list comprehension:
(into {}
(for [[k v] {:a 1 :b nil :c :z} :when (not (nil? v))]
[k v]))
I would use:
(into {} (filter (comp some? val) {:a :x, :b nil, :c :z}))
=> {:a :x, :c :z}
Doing the some? check explicitly is important because if you just do (into {} (filter val {...}))
then you will erroneously remove values that are boolean false.
I use following code:
(into {} (filter val {:a 1, :b 2, :c nil}))
;;=> {:a 1, :b 2}
NOTE: this will remove false values as well as nils
(into {} (keep (fn [e] (if (val e) e)) {:a :x :b nil :c :z}))
;;=> {:a :x, :c :z}
or a little shorter:
(into {} (keep #(if (val %) %) {:a :x :b nil :c :z}))
In fact, your filter suggestion is much better and shorter, so I would just use that:
(into {} (filter val {:a :x :b nil :c :z}))