Remove nil values from a map?

2020-05-29 19:24发布

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}

标签: clojure
9条回答
等我变得足够好
2楼-- · 2020-05-29 20:01

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}  
查看更多
Explosion°爆炸
3楼-- · 2020-05-29 20:01

A variation on @Eelco's answer:

(defn remove-nils [m]
  (let [f (fn [x]
            (if (map? x)
              (let [kvs (filter (comp not nil? second) x)]
                (if (empty? kvs) nil (into {} kvs)))
              x))]
    (clojure.walk/postwalk f m)))

To @broma0's point, it elides any empty maps.

user> (def m {:a nil, :b 1, :c {:z 4, :y 5, :x nil}, :d {:w nil, :v nil}})
user> (remove-nils m)
{:b 1, :c {:z 4, :y 5}}
user> (remove-nils {})
nil
查看更多
够拽才男人
4楼-- · 2020-05-29 20:01

reduce-kv can also be used to remove the keys

(reduce-kv (fn [m key value]
                (if (nil? value)
                  (dissoc m key)
                  m))
            {:test nil, :test1 "hello"}
            {:test nil, :test1 "hello"})
查看更多
该账号已被封号
5楼-- · 2020-05-29 20:02

You could squish it into a map:

(into {} (remove (fn [[k v]] (nil? v)) {:a 1 :b 2 :c nil}))
=> {:a 1 :b 2}
查看更多
一纸荒年 Trace。
6楼-- · 2020-05-29 20:03

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:

user> (select-keys record (for [[k v] record :when (not (nil? v))] k))
{:b 2, :a 1}
查看更多
Melony?
7楼-- · 2020-05-29 20:10

You can use reduce.

user> (reduce (fn [m [k v]] (if (nil? v) m (assoc m k v))) {} record)
{:b 2, :a 1}

If for some reason you want to keep the ordering (which is usually not important in a map), you can use dissoc.

user> (reduce (fn [m [k v]] (if (nil? v) (dissoc m k) m)) record record)
{:a 1, :b 2}
查看更多
登录 后发表回答