[英]Transforming a map with assoc and dissoc at the same time in clojure
我有一张地图,如下所示。 我从数据数据库中获取信息。 现在我想在这里转换数据结构:
(def my-map [{:db/id #object[Object 56536887900242005],
:height 630,
:distance 1474.1,
:coordinates [-26.65622109697031 30.48401767312403],
:location #:location{:id 1}}
{:db/id #object[Object 56536887900242006],
:height 22075,
:distance 1503.2,
:coordinates [-26.65622109697031 30.48401767312403],
:location #:location{:id 2}}
{:db/id #object[Object 56536887900242007],
:height 24248,
:distance 1695.6,
:coordinates [-26.662030943549 30.25648873549992],
:location #:location{:id 3}})
看起来像这样
{1 {:height 630, :distance 1474.1,:coordinates [-26.65622109697031 30.48401767312403]}
2 {:height 22075, :distance 1503.2,:coordinates [-26.65622109697031 30.48401767312403]}
3 {:height 24248, :distance 1695.6,:coordinates [-26.65622109697031 30.48401767312403]}}
我想从拉1 #:location{:id 1}
我会再assoc
用
{:height 22075, :distance 1503.2,:coordinates [-26.65622109697031 30.48401767312403]}
波纹管我有返回上述内容的代码,但我不知道如何将其assoc
到:id
并且我也不知道如何获取 id 看到数据具有#
(map #(dissoc % :db/id :location ) my-map)
无论如何,我在每个项目中都使用plumbing.core
,如果您也这样做,那么此解决方案可能会吸引您。
(grouped-map
(fn-> :location :location/id)
(fn-> (dissoc :location :db/id))
my-map)
您可以这样写:
(into {}
(map
#(hash-map
(get-in % [:location :location/id])
(dissoc % :db/id :location))
my-map))
有时使用for
可以帮助使数据的结构更加明显:
(->> (for [record my-map]
[(-> record :location :location/id)
(dissoc record :db/id :location)])
(into {}))
以下函数可以解决问题:
(defn transform [coll]
(->> coll
(map #(hash-map
(-> % :location :location/id)
(dissoc % :db/id :location)))
(into {})))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.