Flattening a map by join the keys

前端 未结 1 1863
予麋鹿
予麋鹿 2021-01-02 04:08

Given a nested map with only keyword keys such as {:foo {:bar 1 :baz [2 3] :qux {:quux 4}} :corge 5}, how can I implement flatten-map so that

相关标签:
1条回答
  • 2021-01-02 04:43
    (defn flatten-map
      ([form separator]
         (into {} (flatten-map form separator nil)))
      ([form separator pre]
         (mapcat (fn [[k v]]
                   (let [prefix (if pre (str pre separator (name k)) (name k))]
                     (if (map? v)
                       (flatten-map v separator prefix)
                       [[(keyword prefix) v]])))
                   form)))
    

    you were unconditionally creating new key / value pairs, even when the value was to be expanded, so I switched map to mapcat so that a result could be "subsumed" into the top level (this also required splitting the (into {} ...) into the top level version of the form, since we don't actually want any maps anywhere but the top level of the output).

    Here is how it works with your example:

    user> (flatten-map {:foo {:bar 1 :baz [2 3] :qux {:quux 4}} :corge 5} "-")
    {:foo-bar 1, :foo-qux-quux 4, :foo-baz [2 3], :corge 5}
    
    0 讨论(0)
提交回复
热议问题