Say I have a collection of maps:
(def coll #{{:name "foo"} {:name "bar"}})
I want a function that will add an id (a unique number is fine) to each map element in the collection. i.e.
#{{:id 1 :name "foo"} {:id 2 :name "bar"}}
The following DOES NOT WORK, but it's the line of thinking I currently have.
(defn add-unique-id [coll]
(map assoc :id (iterate inc 0) coll))
Thanks in advance...
If you want to be really, really sure the IDs are unique, use UUIDs.
(defn add-id [coll] (map #(assoc % :id (str (java.util.UUID/randomUUID))) coll))
How about
(defn add-unique-id [coll]
(map #(assoc %1 :id %2) coll (range (count coll))))
Or
(defn add-unique-id [coll]
(map #(assoc %1 :id %2) coll (iterate inc 0)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With