nilo de roock
nilo de roock

Reputation: 4157

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

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

Answers (1)

Chris Murphy
Chris Murphy

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

Related Questions