Reputation: 4157
Consider the following hypothetical code
(def db (atom [
{:id 1 :data {:name "Foo"} :par nil}
{:id 2 :data {:name "Bar"} :par nil}]))
db is an atom containing a vector of maps.
Now, I want to make a function that updates the value of a key in one of the maps, for example:
(defn update [id value]
-- update
-- in db atom as defined above
-- where :id is equal to id
-- set :par to value
)
How can this be done?
Upvotes: 1
Views: 229
Reputation: 6509
Here's the function:
(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)))
)
And calling it:
(defn example []
(update-par 1 "new value"))
=> (example)
[{:id 1, :data {:name "Foo"}, :par "new value"} {:id 2, :data {:name "Bar"}, :par nil}]
Upvotes: 1