Last active
November 29, 2023 00:26
-
-
Save sudodoki/023d5f08c2f847b072b652687fdb27f2 to your computer and use it in GitHub Desktop.
Flatten nested maps using clojure / clojurescript using compound keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn get-key | |
[prefix key] | |
(if (nil? prefix) | |
key | |
(str prefix "-" key))) | |
(defn flatten-map-kvs | |
([map] (flatten-map-kvs map nil)) | |
([map prefix] | |
(reduce | |
(fn [memo [k v]] | |
(if (map? v) | |
(concat memo (flatten-map-kvs v (get-key prefix (name k)))) | |
(conj memo [(get-key prefix (name k)) v]))) | |
[] map))) | |
(defn flatten-map | |
[m] | |
(into {} (flatten-map-kvs m))) | |
(flatten-map {:a 12 :fromUser { :id 12 :url "something"}}) | |
; {"a" 12, "fromUser-id" 12, "fromUser-url" "something"} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn jsonify-values | |
"Recursively transforms all map values from json string to clj." | |
[m] | |
(let [f (fn [[k v]] (try [k (json/read-str v)] (catch Exception e [k v])))] | |
;; only apply to maps | |
(walk/postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I need to flatten the vector also.
ex. {r: 6, a: [{b:6},{b:4}]} ---> {r:6 , {[a_b: 6] [a_b: 4]}}