[英]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"]}
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)))
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. Clojure具有name
, symbol
和keyword
功能,可在字符串和符号/关键字之间进行转换。 Since you already have the ID as a string, you just need to call keyword
to convert it. 由于您已经拥有ID作为字符串,因此您只需调用keyword
即可将其转换。
Be sure to always keep a browser tab open to The Clojure CheatSheet . 确保始终将浏览器选项卡打开到The Clojure CheatSheet 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.