1

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?

3
  • something like this: (some #(when (= "city" (:key %)) (:value %)) (data :current-attributes)) Commented Dec 18, 2019 at 12:08
  • @leetwinski woahh.. you're genius. It's worked. I've been strugling for this. How can I upvote your answer? Thanks Commented Dec 18, 2019 at 12:10
  • 1
    If you want to get a value at a known path within a data structure like data you can use get-in e.g. (get-in data [:current-attributes 1 :value]). Commented Dec 18, 2019 at 12:36

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.