简体   繁体   中英

Transforming a map with assoc and dissoc at the same time in clojure

I have a map as seen bellow. I am getting the information from a datomic database. Now I want to transform the data structure here:

(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}})

to look like this

{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]}}

I want to pull the 1 from #:location{:id 1} which I will then assoc with

{:height 22075, :distance 1503.2,:coordinates [-26.65622109697031 30.48401767312403]}

Bellow I have code that return the above, but I do not know how to assoc it into the :id and I also do not know how to get the id seeing that the data has a #

(map #(dissoc % :db/id :location ) my-map)

I use plumbing.core in every project anyway, and if you do as well, then this solution might appeal to you.

(grouped-map
    (fn-> :location :location/id)
    (fn-> (dissoc :location :db/id))
    my-map)

You can write like this:

(into {} 
  (map
    #(hash-map 
       (get-in % [:location :location/id]) 
       (dissoc % :db/id :location))
    my-map))

Sometimes using for can help make the structure of your data more apparent:

(->> (for [record my-map]
       [(-> record :location :location/id)
        (dissoc record :db/id :location)])
     (into {}))

The following function will do the trick:

(defn transform [coll]
  (->> coll
       (map #(hash-map
               (-> % :location :location/id)
               (dissoc % :db/id :location)))
       (into {})))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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