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

时间:2016-04-26 13:53:44

标签: clojurescript

考虑以下假设代码

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

如何做到这一点?

1 个答案:

答案 0 :(得分:1)

这里的功能是:

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