Assoc new key to every map in a list in Clojure

Given some function that computes a value given base on a map

(defn some-function [element] "some computation over element") 

Is there a idomatic way of assoc'ing a new key for each element in a list of maps, where the value of the new key is computed by some-function?

Here is my naive approach:

(map (fn [element] (assoc element :newkey (some-function element))) [{:a "map 1"} {:a "map 2"}]) 

1 Answer

Your code looks fine.

But you may consider using #() special macro instead of creating anonymous function yourself:

(map #(assoc % :newkey (some-function %)) [{:a "map 1"} {:a "map 2"}]) 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like