简体   繁体   English

如何从Clojure Array中的键获取特定值?

[英]How to get specific value from key in Clojure Array?

I have data in clojure defined as:我在 clojure 中有数据定义为:

(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.但是:current-attributes的值本质上就像一张地图。 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: my-new-data最终会变成这样:

{: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.获取城市只是一个嵌套的地图查找,可以使用(get-in my-new-data [:current-attributes "city"])此外, :current-attributes不是特定的,除非它可能包含:actor作为关键,或者在某些情况下具有您关心的特定含义,可以被展平。

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:另外,假设current-attributes中key的名字是程序化的名字,按照Clojure中keywords的语法,你可以把它们转换成keywords,然后全部倒入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)提取城市只是说, (:city my-newer-data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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