Here's one method:
(some #(if (= "GEICO" (:name %)) %) testVMap)
That says: Return the first thing in testVMap
whose :name
is equal to "GEICO"
. #(... % ...)
defines a function, with %
as its function parameter. This part (:name %)
returns the value of the :name
value for each map.
If there might be multiple "GEICO" maps, and you want them all, use filter
instead of some
.
Here's another version:
(some #(and (= "GEICO" (:name %)) %) testVMap)
You may want to use update
as well.
EDIT:
e.g.:
(map #(if (= "GEICO" (:name %))
(update % :rate inc)
%)
testVMap)
Here inc
is the function that adds 1 to a number. You should replace that with a function that performs the transformation that you want, such as #(+ 10 %)
, or (partial + 10)
, which is the same thing.
The function defined by #(...)
checks whether the value of :name
is "GEICO", and then if so, updates the rate with the function that you provide (inc
in this case); otherwise, #(...)
returns the map unchanged.
I'll leave it to you to look up the documentation of update
, if it's not self-explanatory from the context.
You could also use mapv
instead of map
.
You'll no doubt want to build all of this into one or more functions. Remember that functions are things in Clojure--they're "data", first class objects, etc. So where I used inc
, you can have a function parameter, and the function you define can accept another function as its argument, which the first function will then use in the update
part of the code (instead of inc
).
About adding a map if the one you want doesn't exist: If you're not dealing with a long sequence of maps, I'd consider doing this in a different step. See Andre's answer for names of functions that are useful for testing whether a collection contains an element.
However, note that testing whether a vector contains something that's not there requires Clojure to look through the entire vector. It might be better to use a Clojure set rather than a vector, or consider using an outer map with (for example) :aaa
, :geico
, etc. as keys. In that case, take a look at the function update-in
.