Calculating a value and adding it to a map
clojure
Solution
In clojure, "adding to a map" is done with assoc, which returns a new map with the specified value(s) added, and usually if you want to do the same operation on a collection of things, you use the `map` function.
(defn subcount
"return the number of items in the :sub of m"
[m]
(count (:sub m)))
(defn add-count
"add subcount to the given map"
[m]
(assoc m :subcount (subcount m)))
(defn add-counts
"add subcount to all the objects"
[objects]
(map add-count objects))
(def mylist
[{:id 1 :sub [{:subid 1} {:subid 2}]}
{:id 2 :sub [{:subid 3}]}])
(add-counts mylist)
=> ({:sub [{:subid 1} {:subid 2}], :subcount 2, :id 1} {:sub [{:subid 3}], :subcount 1, :id 2})
Problem
I have a list of maps: ``` (def mylist [{:id 1 :sub [{:subid 1} {:subid 2}]} {:id 2 :sub [{:subid 3}]}]) ``` I want to add a new key/value pair to each map element of the list that contains the count of items in `:sub`: ``` [{:id 1 :sub [{:subid 1} {:subid 2}] :subcount 2} {:id 2 :sub [{:subid 3}] :subcount 1}] ``` How can I do this?