4

How can I convert this function (into Clojurescript) that takes a JavaScript object and pushes it's contents into an array.

function toKeyValueList(obj) {
  var arr = [];

  for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
      arr.push({
        key: key,
        value: obj[key]
      });
    }
  }

  return arr;
} 

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;    

(defn toKeyValueList [obj]
  ????
)
Henry Zhu
  • 3,443
  • 5
  • 24
  • 36

1 Answers1

4

The following would be the ClojureScript equivalent:

(defn key-value [obj]
  (loop [acc [] ks (.keys js/Object obj)]
    (if (seq ks)
      (recur (conj acc (clj->js {(first ks) (aget obj (first ks))})) (rest ks))
      (clj->js acc))))

or alternatively using reduce instead of loop/recur:

(defn key-value [obj]
  (clj->js
   (reduce (fn [acc k]
             (conj acc (clj->js {k (aget obj k)})))
           []
           (.keys js/Object obj))))
Symfrog
  • 3,248
  • 1
  • 14
  • 13