且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Clojure中有条件地初始化映射的元素

更新时间:2023-02-20 18:59:50

我会使用 merge

I would use a combination of merge and when-let for these optional parameters.

核心思想是合并单个元素映射或每个可选参数的nil。合并为nil将不会执行任何操作,因此您不会在地图中看到nil。

The core idea is to merge in either a single element map or nil for each of the optional parameters. Merging in nil will do nothing, so you won't see the nil in the map.

(defn create-record [data]
  (let [res (merge {:username (data :username)
                    :first-name (get-in data [:user-info :name :first])
                    :last-name (get-in data [:user-info :name :last])}
                   (when-let [gender (get-in data [:user-info :sex])]
                     {:gender gender}))]
    res))

,我建议写一个简短的宏或函数来保持代码更简洁。

Depending on how frequently you need to do this, I would recommend writing a short macro or function around the when-let to keep the code more concise.