我的数据结构与
类似[{:Gender "Boy" :Cat1 "Foo" :Cat2 "Bar" :SKU 111}
{:Gender "Boy" :Cat1 "Foo" :Cat2 "Bar" :SKU 222}
{:Gender "Girl" :Cat1 "Foo" :Cat2 "Bar" :SKU 333}
{:Gender "Boy" :Cat1 "Foo" :Cat2 "Woo" :SKU 444}]
我想构建一个看起来像
的数据结构 [{:Name "Boy"
:Children
{ :Name "Foo"
:Children
{:Name "Bar"
:Children
{:SKU 111}
{:SKU 222}
}
{:Name "Woo"
:Children
{:SKU 444}
}
}
{:Name "Girl"
:Children
{:Name "Foo"
:Children
{:Name "Bar"
:Children
{:SKU 333}
}
}
}]
我是Clojure的新手,所以如果答案很明显,请原谅。
答案 0 :(得分:0)
不完全是你想要的,但可能很接近:
user=> (def foo [{:Gender "Boy" :Cat1 "Foo" :Cat2 "Bar" :SKU 111}
#_=> {:Gender "Boy" :Cat1 "Foo" :Cat2 "Bar" :SKU 222}
#_=> {:Gender "Girl" :Cat1 "Foo" :Cat2 "Bar" :SKU 333}
#_=> {:Gender "Boy" :Cat1 "Foo" :Cat2 "Woo" :SKU 444}])
#'user/foo
user=> (group-by (juxt :Gender :Cat1 :Cat2) foo)
{["Boy" "Foo" "Bar"] [{:Gender "Boy", :Cat2 "Bar", :Cat1 "Foo", :SKU 111}
{:Gender "Boy", :Cat2 "Bar", :Cat1 "Foo", :SKU 222}],
["Girl" "Foo" "Bar"] [{:Gender "Girl", :Cat2 "Bar", :Cat1 "Foo", :SKU 333}],
["Boy" "Foo" "Woo"] [{:Gender "Boy", :Cat2 "Woo", :Cat1 "Foo", :SKU 444}]}
user=> (def foo2 (group-by (juxt :Gender :Cat1 :Cat2) foo))
#'user/foo2
user=> (zipmap (keys foo2) (map #(map :SKU %) (vals foo2)))
{["Boy" "Foo" "Woo"] (444), ["Girl" "Foo" "Bar"] (333), ["Boy" "Foo" "Bar"] (111 222)}
答案 1 :(得分:0)
以下是解决方案(注意::Children
应该是地图列表)
(def data [{:Gender "Boy" :Cat1 "Foo" :Cat2 "Bar" :SKU 111}
{:Gender "Boy" :Cat1 "Foo" :Cat2 "Bar" :SKU 222}
{:Gender "Girl" :Cat1 "Foo" :Cat2 "Bar" :SKU 333}
{:Gender "Boy" :Cat1 "Foo" :Cat2 "Woo" :SKU 444}])
(defn gp-by [data key]
(->> (group-by key data)
(map (fn [[k v]] {:Name k
:Children (map #(dissoc % key) v)}))))
(map (fn [m] (assoc m :Children
(map (fn [n] (assoc n :Children (gp-by (n :Children) :Cat2)))
(gp-by (m :Children) :Cat1)))) (gp-by data :Gender))