Artem
Artem

Reputation: 2047

Clojure: set value as a key

May be, it is a stupid question, but it may help many of newbies. How do I add a key-value pair to the map?

I mean something like:

(defn init-item [v item]
  (let [{:keys [id value]} item]
    (-> v
        (assoc :{ID_AS_A_KEY} value))))

And I get:

(init-item {} {:id "123456789" :value [:name "King" :surname "Leonid"]})
user=> {:123456789 [:name "King" :surname "Leonid"]}

Upvotes: 0

Views: 789

Answers (2)

amalloy
amalloy

Reputation: 92012

Just don't do it. Use the string itself as your map key. There's no reason to make it a keyword. It's much easier to work with if you leave it alone.

(defn init-item [v item]
  (assoc v (:id item) (:value item)))

Upvotes: 5

Alan Thompson
Alan Thompson

Reputation: 29956

I think this is what you meant to do:

  (defn init-item
    [dest-map item]
    (let [item-id-str (:id item)
          item-val    (:value item)
          item-id-kw  (keyword item-id-str)]
      (assoc dest-map item-id-kw item-val)))

  (let [all-items {:a 1 :b 2 :c 3}
        item-1    {:id    "123456789"
                   :value [:name "King" :surname "Leonid"]}]

(init-item all-items item-1)  
  ;=>  {:a 1, :b 2, :c 3, :123456789 [:name "King" :surname "Leonid"]}

Clojure has functions name, symbol, and keyword to convert between strings and symbols/keywords. Since you already have the ID as a string, you just need to call keyword to convert it.

Be sure to always keep a browser tab open to The Clojure CheatSheet.

Upvotes: 1

Related Questions