I am trying to write a function that looks through an array of objects (the first argument) and returns an array of all objects that contain all the key / value pairs of the given object (second argument).
My code below only works if the object source(second argument) contains one key / value pair. If the object sourcehas two or more key / value pairs, the result is not as expected.
How to account for multiple key / value pairs in an object source?
function findObjects(collection, source) {
var result = [];
for (i=0; i<collection.length; i++) {
for (var prop in source) {
if (collection[i].hasOwnProperty(prop) && collection[i][prop] == source[prop]) {
console.log('Collection\ object ' + [i] + ' contains the source\ key:value pair ' + prop + ': ' + source[prop] + '!');
result.push(collection[i]);
} else {
console.log('fail');
}
}
}
console.log('The resulting array is: ' + result);
return result;
}
findObjects([{ "a": 1, "b": 2 }, { "a": 1 }, { "b": 2, "c": 2 }], { "a": 1, "b": 2 });
source
share