【问题标题】:Transforming a map with assoc and dissoc at the same time in clojure在 clojure 中同时使用 assoc 和 dissoc 转换地图
【发布时间】:2019-08-22 19:26:31
【问题描述】:

我有一张如下图所示的地图。我正在从一个原子数据库中获取信息。现在我想在这里转换数据结构:

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

我想从 #:location{:id 1} 中提取 1,然后我将使用 assoc

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

下面我有返回上述内容的代码,但我不知道如何将assoc 转换为:id,而且我也不知道如何获取ID,因为数据有#

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

【问题讨论】:

  • 这样的事情可以解决问题:(reduce #(assoc %1 (-> %2 :location :location/id) (dissoc %2 :db/id :location)) {} my-map)
  • 或像这样:(into {} (map (juxt (comp :location/id :location) #(dissoc % :location :db/id))) my-map)
  • @leetwinski 如果你想回答你应该发布一个答案。

标签: clojure clojurescript


【解决方案1】:

无论如何,我在每个项目中都使用plumbing.core,如果你也这样做,那么这个解决方案可能会吸引你。

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

【讨论】:

    【解决方案2】:

    你可以这样写:

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

    【讨论】:

      【解决方案3】:

      有时使用for 可以帮助使您的数据结构更加明显:

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

      【讨论】:

        【解决方案4】:

        以下函数可以解决问题:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-12-18
          • 2014-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-11-14
          • 1970-01-01
          相关资源
          最近更新 更多