简体   繁体   中英

How to get specific value from key in Clojure Array?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM