简体   繁体   中英

Clojure: adding to a map

If I have a vector of maps

(def v [{:key1 "value 1" :key2 "value2"} {:key1 "value 3" :key2 "value4"}])

and a map

(def m {:key3 "value2" :key4 "value5"})

How to add map m to all the maps in vector v where the values of 2 given keys (in this case key2 and key3) are equal?

The expected result would be this:

[{:key1 "value 1" :key2 "value2" :key3 "value2" :key4 "value5"} {:key1 "value 3" :key2 "value4"}]

You want to merge each map with m3 if key2 and k3 are equal:

(map (fn [x] (if (= (:key2 x) (:key3 m)) (merge m x) x)) v)

=>

({:key3 "value2", :key2 "value2", :key4 "value5", :key1 "value 1"} {:key2 "value4", :key1 "value 3"})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM