我有兴趣使用Clojurescript中的核心函数创建如下所示的函数。
var props = [
["eyes", "brown"],
["age", "20"]
];
var people = [
{eyes: "brown", age: "20", name: "Dick"},
{eyes: "green", age: "30", name: "Tom"},
{eyes: "blue", age: "20", name: "Sally"},
{eyes: "brown", age: "20", name: "Harry"}
];
find = function (items, keyvals) {
var results = items.slice(0);
keyvals.forEach(function (keyval) {
results = results.reduce(function (memo, item) {
if (item.hasOwnProperty(keyval[0]) &&
item[keyval[0]] === keyval[1]) {
memo.push(item);
}
return memo;
}, []);
});
return results;
};
document.body.innerHTML = JSON.stringify(find(people, props));
到目前为止,我有:
(defn find-all
([items k v]
(filter #(= (k %) v) items))
([items k v & keyvals]
(into [k v] keyvals)))
上述函数的第二部分会为每个(find-all items k v)
调用keyvals
,存储生成的匹配项,然后将这些匹配项提供给下一个调用项。 items
将是一个地图矢量,而不是一个对象数组。
答案 0 :(得分:0)
看一下(source clojure.set/index)
的灵感。
(def props {:eyes "brown", :age "20"})
(def people #{{:eyes"brown", :age "20", :name "Dick"}
{:eyes "green", :age "30", :name "Tom"}
{:eyes "blue", :age "20", :name "Sally"}
{:eyes "brown", :age "20", :name "Harry"}})
((clojure.set/index people (keys props)) props)
;=> #{{:eyes "brown", :age "20", :name "Harry"}
{:eyes "brown", :age "20", :name "Dick"}}