如何在 ClojureScript 中更新地图向量中地图的值?

How to update, in ClojureScript, a value of a map in a vector of maps?

考虑以下假设代码

(def db (atom [ 
 {:id 1 :data {:name "Foo"} :par nil}
 {:id 2 :data {:name "Bar"} :par nil}]))

db 是一个包含映射向量的原子。

现在,我想创建一个函数来更新其中一个映射中的键的值,例如:

(defn update [id value]
 -- update 
 -- in db atom as defined above
 -- where :id is equal to id
 -- set :par to value
)

如何做到这一点?

函数如下:

(defn update-par [id value]
  ;; update
  ;; in db atom as defined above
  ;; where :id is equal to id
  ;; set :par to value
  (swap! db (fn [v] (mapv (fn [item] (if (= (:id item) id) (assoc item :par value) item)) v)))
)

并调用它:

(defn example []
  (update-par 1 "new value"))

=> (example)
[{:id 1, :data {:name "Foo"}, :par "new value"} {:id 2, :data {:name "Bar"}, :par nil}]