2014-11-23 52 views
1

我正在使用clojurescript 0.0-2371,我试图编写一些代码来克隆一个对象。我有这样的代码,我想克隆一个节点,并调用clone-object功能:clojurescript遍历对象的键

(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)) 

我收到此错误:

Uncaught Error: [object Object] is not ISeqable

回答

8

答案是使用goog.object.forEach

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

为什么'key'参数? – Marcs 2016-09-22 15:37:48

1

你不严格需要关闭谷歌通过按键循环:

(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采用由密钥k称为的obj属性。
  • (.keys js/Object obj)获取js对象的所有密钥。