What is the idiomatic way to cut a map in Clojure?

For lists and vectors, we can cut off the sequence and take whatever part we want. How to perform similar operations to match objects?

For example, I have a list of map objects,

(def plays [
        {:name "Burial",     :plays 979,  :loved 9}
        {:name "Eno",        :plays 2333, :loved 15}
        {:name "Bill",       :plays 979,  :loved 9}
        {:name "Magma",      :plays 2665, :loved 31}])

For each display, I want to cut off the playback column and add a speed column with a default value, what is the idiomatic way to do this?

+5
source share
2 answers

assocand dissocare your friends in this case:

(map #(-> % (dissoc :plays) 
            (assoc :rate 10)) plays)
+17
source

Depending on your use case, you may also find select-keysuseful in addition to assocand dissoc:

clojure.core/select-keys
([map keyseq])
  Returns a map containing only those entries in map whose key is in keys
(select-keys {:name "Eno" :plays 2333 :loved 15} [:name :loved])
;; => {:name "Eno" :loved 15}
+13
source

All Articles