1 回答
TA贡献1906条经验 获得超3个赞
我的思路是一个对象数组collection的数组元素item包含相匹配的对象source, 那么在判断key-value的个数是等于source对象中key的个数. 实现代码:
function where(collection, source) {
return collection.filter(function(item) {
var index = 0;
for (var key in source) {
if (item[key] && source[key] === item[key]) {
index++;
}
}
return index === Object.keys(source).length;
});
}
var testCaseArray1 = [{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }],
testCaseArray2 = [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }];
var object1 = { "a": 1, "c": 2 },
object2 = { last: "Capulet" };
var testCase1 = where(testCaseArray1, object1),
testCase2 = where(testCaseArray2, object2);
console.log(testCase1);
console.log(testCase2);
添加回答
举报