如何在 clojure 中进行简单的数据规范化



我有这个地图向量:

(def db 
 [{:id "foo" :content "foo-content" :tags []}
  {:id "bar" :content "bar-content" :tags []}
  {:id "baz etc" :content "baz-content" :tags []}])

我想转换它以获得一个地图地图,可以通过 id 直接访问值,如下所示:

{:foo {:content "foo-content" :tags []}
 :bar {:content "bar-content" :tags []}
 :baz-etc {:content "baz-content" :tags []}

这是我的尝试:

(defn normalize [db]
  (into {}
    (for [item db]
      [(:id item) (dissoc item :id)])))

如何做得更好(关键转换?更多的东西要考虑?(?

有我可以使用的库吗?

谢谢!

您可以使用

keyword函数将字符串转换为关键字。

(defn normalize [db]
   (into {}
     (for [item db]
       [(keyword (:id item)) (dissoc item :id)])))

您也可以使用 clojure.walk/keywordize-keys .

(defn normalize [db]
  (clojure.walk/keywordize-keys
   (into {}
     (for [item db]
       [(:id item) (dissoc item :id)]))))

但是有一个问题。 "baz etc"将被转换为:baz etc .因此,在将函数应用于 id 字符串之前,您必须替换空格以- keyword

正如@amalloy提到的,将字符串从文件/数据库转换为关键字不是一个好主意。这些应保留为字符串。

无论如何,如果您确实需要将字符串转换为关键字,则可以使用上述方法。

最新更新