I'm creating a function that takes the first argument, an array of objects, and compares it to the second argument (an object) to see if the key/value pair match. The function would return the object that contains the matching key/value pair. I'm using both filter
, and hasOwnProperty
on the keys,to compare, like so:
function whatIsInAName(collection, source) {
var result = collection.filter(el => {
return el == Object.keys(el).hasOwnProperty(Object.keys(source)) === true;
});
}
return result;
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio",
last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
In the example above the function would return { first: "Tybalt", last: "Capulet" }
I'm filtering the first argument and comparing the keys with the second argument attempting to return the keys of both objects to compare, however I'm very confused how this should work. Namely, how would I go about comparing the values in addition to the keys, if that's what is required as the solution? I do understand there are other methods to get the answer but I would like to grasp hasOwnProperty
and where I'm going wrong in my logic. Thank you.