对于列表和向量,我们可以对序列进行切片并获取我们想要的任何部分。 如何对映射对象进行类似的操作?
例如,我有一个地图对象列表
(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}])
对于每张地图,我想切掉播放列,并添加默认值的rate列,这是什么惯用方法呢?
答案 0 :(得分:17)
assoc
和dissoc
是您的朋友:
(map #(-> % (dissoc :plays)
(assoc :rate 10)) plays)
答案 1 :(得分:13)
根据您的使用情况,除了select-keys
和assoc
之外,您还可能会发现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}