Filtering a collection of arrays

I’m having some trouble understanding why this code works.


function whatIsInAName(collection, source) {
var srcKeys = Object.keys(source);

return collection.filter(function(obj) {
  return srcKeys.every(function(key){
    return obj.hasOwnProperty(key) && obj[key] === source[key]
  });
});
}

// test here
whatIsInAName(
[
  { first: "Romeo", last: "Montague" },
  { first: "Mercutio", last: null },
  { first: "Tybalt", last: "Capulet" }
],
{ last: "Capulet" }
);

Is obj.hasOwnProperty(key) not enough to check if the key is in the object? Why do we need obj[key] === source[key]?

Challenge: Wherefore art thou

Link to the challenge:

Because you need to check if the value matches as well, not just that the key exists.

I am on my phone, so I cant see all of it but it looks like the challenge is to return the name and the value of the array of objects. Like what was said above, if you only used hasOwnProperty your just returning if the key exist or not. Thats why you need === to make sure you’re returning the value of the key as well

if the key exists in the object, doesn’t that mean that the value already matches?

No, not in any way.

{ name: "DanCouper" }
{ name: "Metry" }
2 Likes