ClojureScript - convert arbitrary JavaScript object to Clojure Script map

前端 未结 4 1479
野趣味
野趣味 2021-02-13 20:10

I am trying to convert a Javascript object to a Clojure. However, I get the following error :

 (js/console.log (js->clj e)) ;; has no effect
 (pprint (js->         


        
4条回答
  •  余生分开走
    2021-02-13 20:34

    (defn obj->clj
      ([obj]
       (obj->clj obj :keywordize-keys false))
      ([obj & opts]
       (let [{:keys [keywordize-keys]} opts
             keyfn (if keywordize-keys keyword str)]
         (if (and (not-any? #(% obj) [inst? uuid?])
                  (goog.isObject obj))
           (-> (fn [result k]
                 (let [v (goog.object/get obj k)]
                   (if (= "function" (goog/typeOf v))
                     result
                     (assoc result (keyfn k) (apply obj->clj v opts)))))
               (reduce {} (.getKeys goog/object obj)))
           obj))))
    

    Small problem with the original above is that JS treats #inst and #uuid as objects. Seems like those are the only tagged literals in clojure

    I also added the option to keywordize keys by looking at js->clj source

提交回复
热议问题