Clojure合并哈希映射中的键值

时间:2013-04-26 12:28:28

标签: clojure

所以我有下面的k / v哈希图:

(def data [{:ID "0000010890" :CREDIT "EM 1"}

{:ID "0000010890" :CREDIT "FLOW 1"}

{:ID "0000010890" :CREDIT "EM 1"}

{:ID "0000010890" :CREDIT "FLOW 1"}

{:ID "0000010809" :CREDIT "FLOW 1"}])

我需要合并到这个:

[{:ID "0000010890" :CREDIT "EM 1, FLOW 1"}

{:ID "0000010809" :CREDIT "FLOW 1"}]

有人可以建议在clojure中解决这个问题的最佳方法吗?

我的尝试:

(defn- create-issue-summary-2 [data]
            (->> data
                 (group-by :ID)
                 (map (fn [[k v]] (into {:ID k} (apply merge-with (map #(dissoc % :ID) v)))))))

结果是

({:ID "0000010890", :CREDIT "FLOW 1"} 

{:ID“0000010809”})

1 个答案:

答案 0 :(得分:1)

(map (fn [[k v]]
       (into {} [[:ID k]
                 [:CREDIT (apply str (interpose ", " (distinct (map :CREDIT v))))]]))
     (group-by :ID data))