Remove nil values from a map?

your for list comprehension returns a LIST of maps, so you need to APPLY this list to the merge function as optional arguments:

user> (apply merge (for [[k v] record :when (not (nil? v))] {k v}))
{:b 2, :a 1}      

More concise solution by filtering the map as a sequence and conjoining into a map:

user> (into {} (filter second record))
{:a 1, :b 2}  

Dont remove false values:

user> (into {} (remove (comp nil? second) record))
{:a 1, :b false}  

Using dissoc to allow persistent data sharing instead of creating a whole new map:

user> (apply dissoc                                                                                            
       record                                                                                                  
       (for [[k v] record :when (nil? v)] k))
{:a 1, :b 2}  

Leave a Comment

tech