Skip to content

Instantly share code, notes, and snippets.

@sudodoki
Last active November 29, 2023 00:26
Show Gist options
  • Save sudodoki/023d5f08c2f847b072b652687fdb27f2 to your computer and use it in GitHub Desktop.
Save sudodoki/023d5f08c2f847b072b652687fdb27f2 to your computer and use it in GitHub Desktop.
Flatten nested maps using clojure / clojurescript using compound keys
(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"}
(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)))
@deepakjangid123
Copy link

I need to flatten the vector also.
ex. {r: 6, a: [{b:6},{b:4}]} ---> {r:6 , {[a_b: 6] [a_b: 4]}}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment