简体   繁体   English

转换嵌套Clojure映射

[英]Transform nested clojure maps

I am having trouble transforming a clojure map. 我在转换Clojure地图时遇到麻烦。 The map has a vector as element and the vectors in turn have maps as elements. 地图以向量为元素,向量又以地图为元素。

The original map looks like this: 原始地图如下所示:

{"values" [{"sub" false, "name" "Adhoc"} {"acm" true, "list" true, "deval" true, "name" "Buyer"}]}

The maps within the vector always have the key "name" but the other keys may vary. 向量内的映射始终具有键“名称”,但其他键可能会有所不同。 The name element should act as a key within the map. name元素应充当地图中的键。 As end result I need the original map to be transformed into this: 作为最终结果,我需要将原始地图转换为以下内容:

{"values" {"Adhoc" {"sub" false}, "Buyer" {"deval" true, "acm" true, "list" true}}

The problem is that the maps within the vector can have any amount of elements and I don't really know how to solve that with looping. 问题在于向量中的映射可以包含任意数量的元素,而我真的不知道如何通过循环来解决。 Any suggestions would be highly appreciated. 任何建议将不胜感激。

This would process the vector of maps for you: 这将为您处理地图矢量:

(defn merge-by
  [maps k]
  (->> maps
       (map (juxt #(get % k) #(dissoc % k)))
       (into {})))

(merge-by [{"sub" false, "name" "Adhoc"} 
           {"acm" true, "list" true, "deval" true, "name" "Buyer"}] 
          "name")
;; => {"Adhoc" {"sub" false}, "Buyer" {"deval" true, "acm" true, "list" true}}

And this would process the outer map (if stored in my-map ): 这将处理外部地图(如果存储在my-map ):

(update-in my-map ["values"] merge-by "name")

If you converted the keys to keywords, perc allows you to do this pretty cleanly: 如果您将键转换为关键字,那么perc可以让您很干净地执行此操作:

(->> original-map
  :values
  (mapv #%/%[%:name (dissoc % :name)])
  (into {})
  (#%/%{:values %}))
{:values {"Adhoc" {:sub false}, "Buyer" {:acm true, :list true, :deval true}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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