Search code examples
clojurehashmap

merging maps, but some values are nil


So I have two maps that can be anything and I want to merge them, but not include values that are nil. Let's say I have:

(def x {:a "A" :c 5 :d "D"})
(def y {:a 1 :b 2 :c nil})

I want to end up with

{:a 1 :b 2 :c 5 :d "D"}

I get the wrong value for :c if I just merge like (merge x y), but {:c nil} is there. I do not have control over what two maps come in. Any help would be aappreciated


Solution

  • Using into with the second argument being a filtering transducer results in a piece of code that is both fairly concise and readable:

    (def x {:a "A" :c 5 :d "D"})
    (def y {:a 1 :b 2 :c nil})
    
    (into x (filter (comp some? val)) y)
    ;; => {:a 1, :c 5, :d "D", :b 2}
    

    Only minor tweaks are required to have it remove nils from the first map too, if you need that:

    (def x {:a "A" :c 5 :d "D" :e nil :f nil})
    (def y {:a 1 :b 2 :c nil})
    
    (into {} (comp cat (filter (comp some? val))) [x y])
    ;; => {:a 1, :c 5, :d "D", :b 2}