Reputation: 23
I have data in clojure defined as:
(def data {:actor "damas.nugroho"
:current-attributes [{:key "name", :value "adam"}
{:key "city", :value "jakarta"}]})
and I want to get the city value which means jakarta. How can I do that?
Upvotes: 1
Views: 1292
Reputation: 358
This is the data you have:
(def data
{:actor "damas.nugroho"
:current-attributes [{:key "name", :value "adam"}
{:key "city", :value "jakarta"}]})
And this is how you get at the city:
(->> (:current-attributes data)
(some #(when (= (:key %) "city")
(:value %))))
But the value of :current-attributes
seems like a map, by essence. Assuming the keys don't repeat, consider transforming it into a map for easier manipulation.
(def my-new-data
(update data :current-attributes
#(into {} (map (juxt :key :value)) %)))
my-new-data
will end up becoming this:
{:actor "damas.nugroho"
:current-attributes {"name" "adam"
"city" "jakarta"}}
Getting the city is then just a nested map lookup, and can be done with (get-in my-new-data [:current-attributes "city"])
Also, :current-attributes
is not specific and unless it may contain :actor
as a key, or has a particular meaning you care about in some context, can be flattened.
Also, assuming the names of the keys in current-attributes
are programmatic names, and follow the syntax of keywords in Clojure, you could convert them to keywords, and pour them all into a map:
(def my-newer-data
(let [attrs (into data
(map (juxt (comp keyword :key) :value))
(:current-attributes data))]
(dissoc attrs :current-attributes)))
Now we end up with this:
{:actor "damas.nugroho", :name "adam", :city "jakarta"}
And extracting city is just saying it, (:city my-newer-data)
Upvotes: 4