Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transform ALL keys in map #31

Closed
vincentjames501 opened this issue Oct 20, 2014 · 1 comment
Closed

Transform ALL keys in map #31

vincentjames501 opened this issue Oct 20, 2014 · 1 comment

Comments

@vincentjames501
Copy link

Right now the map-keys function only maps the top keys, i.e:

(map-keys str {:a {:b "c"}})
=> {"a" {:b "c"}}

Can we consider adding something like map-all-keys, map-all-values, etc that will traverse a nested structure? The use case here could be transforming a clojurefied map into a formatted JSON object or vise versa for example.

(defn transform-keys
  "Recursively transforms all map keys in coll with t."
  [t coll]
  (let [f (fn [[k v]] [(t k) v])]
    (clojure.walk/postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) coll)))

(transform-keys ->kebab-case-keyword {"oneTwo" 12 "threeFour" {"fiveSix" 56}})
=> {:three-four {:five-six 56}, :one-two 12}

OR

(defn transform-keys 
  "Recursively transforms all map keys in m with f."
  [f m]
  (letfn [(mapper [[k v]] [(f k) (if (map? v) (map-keys f v) v)])]
    (into {} (map mapper m))))

(transform-keys ->kebab-case-keyword {"oneTwo" 12 "threeFour" {"fiveSix" 56}})
=> {:three-four {:five-six 56}, :one-two 12}
@amalloy
Copy link
Contributor

amalloy commented Oct 20, 2014

No, thanks. You can add this to your own utility library (or a fork of useful), but I don't want it in mine.

@amalloy amalloy closed this as completed Oct 20, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants