1 回答

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
我的思路是一個(gè)對(duì)象數(shù)組collection的數(shù)組元素item包含相匹配的對(duì)象source, 那么在判斷key-value的個(gè)數(shù)是等于source對(duì)象中key的個(gè)數(shù). 實(shí)現(xiàn)代碼:
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);
添加回答
舉報(bào)