2014-11-23 79 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對象的所有密鑰。