简体   繁体   中英

How to get first element map from an array using clojure

I have an array of result ({:a one}) . I want a result which returns one when I select or give :a .

I used vals,get-in functions but since the map is inside a list they are not working. Can you please help me how do I do that.

I need to return value for a given key.

Also,

What if the data is of the form

({:a “Favorite fruit", :measurements [{:a “fav game?", :b "x",
:name “foot ball", :max 7.0, :min 0.0, :id “12345"}], :name “Frequency”})

and I want to select :a "fav game?" :name "foot ball" and :min 0.0 ?

Thank you

Try this:

clj.core=> (def data [ {:a 1} {:b 2} ] )
#'clj.core/data
clj.core=> (:a (first data))
1
clj.core=> (mapv :a data)
[1 nil]

List comprehension

List comprehension using for with any quantity of elements in the list:

(for [x data :let [m (:measurements x)]] (map #(let [{:keys [a name min]} %] [a name min]) m))

Details:

  • for [x data for every element in data
  • :let [m (:measurements x)]] set m as a symbol for :measurements
  • (map #(let [{:keys [a name min]} %] [a name min]) m) for every m get the keys a name min and output a vector [a name min] .

Output:

((["fav name?" "foot ball" 0.0]))

Or one result

Directly using apply :

(let [{:keys [a name min]} (apply (comp first :measurements) data)] [a name min])

Details:

  • (apply (comp first :measurements) data) apply comp osition, first get :measurements then the first elem.
  • let [{:keys [a name min]} get the keys a name min from the map and output a vector [a name min] .

Output:

["fav name?" "foot ball" 0.0]

If you have a vector of results (usually more idiomatic than a list), you can use get in, but with numbers as keys. eg

(get-in [{:a "one"}] [0 :a])  ;=> "one"

To add to @Marcs answer (and for some extra Clojure help) there are a few ways to pull values out using destructuring too.

Starting with the example you gave

(def foobar
  {:a "Favorite fruit", :measurements [{:a "fav game?", :b "x",
   :name "foot ball", :max 7.0, :min 0.0, :id "12345"}], :name "Frequency"})

We can do associative destructuring since Clojure maps are associative data structures

;; associative destructuring
(let [{:keys [a]} foobar]
  a)

;; also associative destructuring in the function params this time
((fn [{:keys [a]}]
   a)
 foobar)

To a get single value out of a map wrapped in an array we can use a combination of sequential and associative destructuring

(let [[{:keys [a]}] '({:a 'one})]
  a)

For the last part you asked about with getting :a :name :min we can use another destructuring combo

(let [{a :a [{min :min}] :measurements name :name} foobar]
  [a name min])

That clojure.org article I linked to is pretty awesome for explaining more details!

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