簡體   English   中英

在clojure中同時使用assoc和dissoc轉換地圖

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM