function where(collection, source) { var arr = []; // What's in a name? var keys = Object.keys(source); arr = collection.filter(function(item){ for (var i = 0; i < keys.length; i ++){ if(!item.hasOwnProperty(keys[i]) || item[keys[i]] !== source[keys[i]]){ return false; } } return true; }); return arr; } where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
另外一种方法
function where(collection, source) { var arr = []; // What's in a name? var keys = Object.keys(source); arr = collection.filter(function(item){ return keys.every(function(key){ return item.hasOwnProperty(key) && item[key] === source[key]; }); }); return arr; } where([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });