[英]Clojure / Clojurescript: group-by a map on multiple values
Given a data structure, I'd like to re-structure it to be grouped by one of the nested values. 给定一个数据结构,我想将其重新构造为按嵌套值之一分组。 These values are vectors, and whenever I encounter more than one value, I'm getting stuck. 这些值是向量,每当遇到多个值时,我都会被卡住。
Given a vector of maps like this: 给定这样的地图向量:
(def tools
[{:name "A",
:config
{:accepts ["id"],
:classes ["X"]}}
{:name "B",
:config
{:accepts ["id"],
:classes ["X", "Y"]
}}])
I can almost get what I want - the values sorted by "classes" as a key, with values repeated if need be - by running group-by
: 我几乎可以得到我想要的-通过运行group-by
,将按“类”排序的值作为键,如果需要的话可以重复这些值:
(group-by #(get-in % [:config :classes]) tools)
But it takes the whole vector in :classes
as the key. 但是这需要在整个向量:classes
为重点。
{["X"] [{:name "A",
:config {:accepts ["id"],
:classes ["X"]}}],
["X" "Y"] [{:name "B",
:config {:accepts ["id"],
:classes ["X" "Y"]}}]}
What I really want is to copy the values once per class, to look like this: 我真正想要的是每个类复制一次值,如下所示:
{"X" [{:name "A"
:config {:accepts ["id"]
:classes ["X"]}}
{:name "B"
:config {:accepts ["id"]
:classes ["X" "Y"]}}]
"Y" [{:name "B"
:config {:accepts ["id"]
:classes ["X" "Y"]}}]}
I'm not quite sure how to handle this given that I have multiple values in classes
. 考虑到我在classes
有多个值,我不太确定如何处理这个问题。
Working repl demo: https://repl.it/@YoYehudi/FamiliarDisguisedXiphiasgladius 工作代表演示: https : //repl.it/@YoYehudi/FamiliarDisguisedXiphiasgladius
Here's a way to do it using a nested reduce
: 这是使用嵌套的reduce
来实现的一种方法:
(defn aggregate-classes [m tool]
(->> (get-in tool [:config :classes])
(reduce (fn [acc elem]
(update acc elem conj tool))
m)))
(reduce aggregate-classes {} tools)
=>
{"X" ({:name "B", :config {:accepts ["id"], :classes ["X" "Y"]}} {:name "A", :config {:accepts ["id"], :classes ["X"]}}),
"Y" ({:name "B", :config {:accepts ["id"], :classes ["X" "Y"]}})}
(apply merge-with into {}
(for [tool tools
class (get-in tool [:config :classes])]
{class [tool]}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.