ClojureScript - convert arbitrary JavaScript object to Clojure Script map

前端 未结 4 1469
野趣味
野趣味 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:44

    Two approaches that do not require writing custom conversion functions - they both employ standard JavaScript functions to loose the custom prototype and thus enable clj->js to work correctly.

    Using JSON serialization

    This approach just serializes to JSON and immediately parses it:

    (js->clj (-> e js/JSON.stringify js/JSON.parse))
    

    Advantages:

    • does not require any helper function
    • works for nested objects, with/without prototype
    • supported in every browser

    Disadvantages:

    • performance might be a problem in critical pieces of codebase
    • will strip any non-serializable values, like functions.

    Using Object.assign()

    This approach is based on Object.assign() and it works by copying all the properties from e onto a fresh, plain (no custom prototype) #js {}.

    (js->clj (js/Object.assign #js {} e))
    

    Advantages:

    • does not require any helper function

    Disadvantages:

    • works on flat objects, if there is another nested object withing e, it won't be converted by clj->js.
    • Object.assign() is not supported by old browsers, most notably - IE.

提交回复
热议问题