Search code examples
clojurelisp

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"]}

Solution

  • 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.