【问题标题】:How to create nested map from array of maps in Clojure?如何从 Clojure 中的地图数组创建嵌套地图?
【发布时间】:2014-10-18 07:04:05
【问题描述】:

所以,作为数据库调用的结果,我得到了一个地图向量,假设它看起来像这样:

[{:make "vw",  :model "vanagon", :color "blue",   :year 1983}
 {:make "vw",  :model "vanagon", :color "red",    :year 1987}
 {:make "vw",  :model "eurovan", :color "blue",   :year 1995}
 {:make "vw",  :model "eurovan", :color "green",  :year 1997}
 {:make "geo", :model "metro",   :color "blue",   :year 1985}
 {:make "geo", :model "metro",   :color "yellow", :year 1994}]

如何使用其中两个字段将其放入嵌套地图中,例如像这样:

{"vw"  {"vanagon" [{:color "blue", :year 1983}, {:color "red", :year 1987}]
        "eurovan" [{:color "blue", :year 1995}, {:color "green", :year 1997}]}
 "geo" {"metro" [{:color "blue", :year 1985}, {:color "yellow", :year 1994}]}}

我已经搞砸了几个小时 group-by 和其他 coll 函数,但我无法完全理解它并想出一个合理的方法来做到这一点。

谢谢!

【问题讨论】:

    标签: clojure


    【解决方案1】:
    (reduce (fn [aggr {:keys [make model] :as row}]
              (update-in aggr
                         [make model]
                         (fnil conj [])
                         (dissoc row :make :model)))
            {} data)
    

    匿名函数执行destructuring bindupdate-in 重写绑定结构。基本思想是使用conj 添加行的其他元素。 fnil 用于指定我们想要向量(当找到 nil 时,使用空向量作为 conj 的第一个参数)。结果由reduce 合并到一张地图中。

    【讨论】:

    • 太棒了!仍然需要完全了解那里发生的事情,但这可以解决问题。谢谢!
    • 但是,如果我不一定知道地图中不用于构建层次结构的所有项目,该怎么办?例如。如果原始地图可能有额外的条目,我希望它们在最后的叶子地图中,而不提前知道它们是什么?
    • 编辑了我的答案以保留任何未用于路径的条目。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-14
    • 2020-04-26
    • 2012-07-19
    • 2014-03-13
    相关资源
    最近更新 更多