2
votes

How to apply a function on every value in a map in vector of maps.

If I have a vector of maps

(def vector-of-maps [{:a 1 :b 2} {:a 3 :b 4}])

And want to apply a function on every value in every map and as a result I want the same vector of maps, something like this

(map #(+ 1 %) vector-of-maps)

So that the result is

[{:a 2 :b 3} {:a 4 :b 5}]

And I want it to work with any vector of maps, not just this particular one....

3

3 Answers

4
votes
=> (defn update-map [m f] (reduce-kv (fn [m k v] (assoc m k (f v))) {} m))
=> (map #(update-map % inc) vector-of-maps)
({:b 3, :a 2} {:b 5, :a 4})
1
votes

Perhaps

(defn mapv-map-values [f vm]
  (letfn [(map-values [m] (zipmap (keys m) (map f (vals m))))]
    (mapv map-values vm)))

... producing

(mapv-map-values inc [{:a 1 :b 2} {:a 3 :b 4}])
;[{:b 3, :a 2} {:b 5, :a 4}]

The map-values function, the only significant departure from @user100464's answer, was adapted from here.

1
votes

also you can do like this,but it is ugly

(defn dodo [m] (map (fn [map] (apply merge (for [[k v] map] (assoc {} k (inc v))))) m))

(dodo [{:a 1 :b 2} {:a 3 :b 4}])
;({:a 2, :b 3} {:a 4, :b 5})