For an exercise, I've written a function that, given an array of objects and a key (2nd argument), returns a new array of objects that contain all properties from a key. How'd I do?
function where(collection, source) {
var arr = [];
var keys = Object.keys(source);
var countMatchingProps = 0;
var currentProp;
for (var i = 0; i < collection.length; i++) {
countMatchingProps = 0;
for(var j = 0; j < keys.length; j++){
// assigned to variable for a bit of readability.
currentProp = keys[j];
// if object contains key ->
if(collection[i].hasOwnProperty(currentProp)){
// -> then compare their values nad increment counter
if(collection[i][currentProp] === source[currentProp]){
countMatchingProps++;
}
}
// if number of matched properties are
// equal to keys we can push current object to array
if (countMatchingProps === keys.length) arr.push(collection[i]);
}
}
return arr;
}
where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 3 }], { "a": 1});
where([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 })