clojurescript迭代对象的键

时间:2014-11-23 08:52:55

标签: clojurescript

我正在使用clojurescript 0.0-2371,我正在尝试编写一些克隆对象的代码。我有这个代码,我想克隆一个节点并调用clone-object函数:

(def animate
  (js/React.createClass
   #js
   {:getInitialState
    (fn []
      (this-as this
               {:children
                (->
                 (.. this -props -children)
                 (js/React.Children.map (fn [child] child))
                 (js->clj :keywordize-keys false))}))
    :render
    (fn []
      (this-as this
               (let [children (:children (.. this -state))]
                 (doseq [[k v] children]
                   (clone-object (aget children k))))))}))

clone-object看起来像这样:

(defn clone-object [obj]
  (log/debug obj)
  (doseq [[k v] obj]
    (log/debug k)))

如果我这样打clone-object

(doseq [[k v] children]
  (clone-object v))

我收到此错误:

  

未捕获错误:[object Object]不是ISeqable

2 个答案:

答案 0 :(得分:8)

答案是使用goog.object.forEach

(defn clone-object [key obj]
  (goog.object/forEach obj
     (fn [val key obj]
        (log/debug key))))

答案 1 :(得分:1)

您并不需要Google Closure来循环访问密钥:

(defn obj->vec [obj]
  "Put object properties into a vector"
  (vec (map (fn [k] {:key k :val (aget obj k)}) (.keys js/Object obj)))
  )

; a random object
(def test-obj (js-obj "foo" 1 "bar" 2))

; let's make a vector out of it
(def vec-obj (obj->vec test-obj))

; get the first element of the vector and make a key value string
(str (:key (first vec-obj)) ":" (:val (first vec-obj)))

关于obj->vec

  • vec将序列转换为向量(如果您对序列没有问题,则可选)
  • map为列表中的每个元素执行(fn [k] ...)
  • (fn [k] ...)获取列表的k元素并将其放入键/值映射数据结构中,aget获取键{{引用的obj属性1}}。
  • k从js对象获取所有密钥。