1

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.

Pbculley
  • 79
  • 8

1 Answers1

1

Iterate over the entries of each el in the collection instead, that way you can test against each key and the associated value at once. The hasOwnProperty check is entirely superfluous:

function whatIsInAName(collection, source) {
  const [[findKey, findVal]] = Object.entries(source);
  return collection.filter(el => (
    Object.entries(el).some(([key, val]) => (
      key === findKey && val === findVal
    )
  )))
}
console.log(
  whatIsInAName([{
    first: "Romeo",
    last: "Montague"
  }, {
    first: "Mercutio",
    last: null
  }, {
    first: "Tybalt",
    last: "Capulet"
  }, {
    first: "another",
    last: "Capulet"
  }, {
    first: "Tybalt",
    last: "notACapulet"
  }], {
    last: "Capulet"
  })
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320