我如何才能将此函数(转换为Clojurescript)转换为一个JavaScript对象,并将其内容推入数组.
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]
????
)
解决方法:
以下将是等效的ClojureScript:
(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))))
或使用reduce代替循环/递归:
(defn key-value [obj]
(clj->js
(reduce (fn [acc k]
(conj acc (clj->js {k (aget obj k)})))
[]
(.keys js/Object obj))))