6

对于列表和向量,我们可以对序列进行切片并获取我们想要的任何部分。如何对映射对象进行类似操作?

例如,我有一个地图对象列表,

(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}])

对于每张地图,我想切掉播放列,并使用默认值添加速率列,这样做的惯用方法是什么?

4

2 回答 2

18

assoc在这种情况下dissoc 是你的朋友:

(map #(-> % (dissoc :plays) 
            (assoc :rate 10)) plays)
于 2013-02-26T06:06:50.760 回答
14

根据您的用例,select-keys除了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}
于 2013-02-26T06:42:31.460 回答