How to remove multiple keys from a map?

前端 未结 4 608
难免孤独
难免孤独 2020-12-29 20:13

I have a function that removes a key from a map:

(defn remove-key [key map]
  (into {}
        (remove (fn [[k v]] (#{key} k))
                map)))

(remov         


        
相关标签:
4条回答
  • 2020-12-29 20:26

    dissoc removes one or more keys from a map:

    (dissoc {:foo 1 :bar 2 :baz 3} :foo :bar)
    

    or, if you have the keys in a collection

    (apply dissoc {:foo 1 :bar 2 :baz 3} [:foo :bar])
    
    0 讨论(0)
  • 2020-12-29 20:36

    As others said use the built-in function instead of writing your own.

    However, if this was just an example and you want an answer of how to do that if there wasn't a standard dissoc, then you can use:

    (reduce (fn [m k] (remove-key k m)) {:foo 1 :bar 2 :baz 3} [:foo :bar])
    

    Obviously, if you revert the arguments to remove-key it can be written much simpler:

    (reduce remove-key {:foo 1 :bar 2 :baz 3} [:foo :bar])
    
    0 讨论(0)
  • 2020-12-29 20:43

    I found this type of thing and others to be super annoying in clojure, so to fix it I created the library instar: https://github.com/boxed/instar .

    0 讨论(0)
  • 2020-12-29 20:52

    Your remove-key function is covered by the standard library function dissoc. dissoc will remove more than one key at a time, but it wants the keys to be given directly in the argument list rather than in a list. So you can use apply to "flatten" it out.

    (apply dissoc {:foo 1, :bar 2, :baz 3} [:foo :bar])
    ==> {:baz 3}
    
    0 讨论(0)
提交回复
热议问题