Search code examples
javascriptclojureclojurescriptomreagent

How to loop a JavaScript object and push each into an array, in Clojurescript


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]
  ????
)

Solution

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