2 tests work but not the last two in object key value comparison

Not really sure why it will pass the first two tests and then return and empty array on the 3rd test. I know just by looking at some of the other solutions there are more elegant ways of doing this but by following the logic I wrote, I cannot understand what the difference in outcome was between the second test (which also returns more than one object) and the third test.

Your code so far

function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line
  for (var i = 0;i < collection.length;i++) {
    if (collection[i].hasOwnProperty(Object.keys(source))) {
      for (var j in collection[i]) {
        if (collection[i][j] === source[j]) {
          arr.push(collection[i]);
        }
      }
    }
  }
  // Only change code above this line
  return arr;
}

whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/wherefore-art-thou

You have the right idea, but the problem here is that hasOwnProperty needs to take just a string. When you pass an array of strings, it will concatenate all of them into one. So, the first two tests pass because the source parameter is an object with just one key. For example, the first test is whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" }). source is the object { last: "Capulet" }. Calling Object.keys on it returns ["last"]. When passed to hasOwnProperty, it automatically gets converted to a string, “last”. That’s (accidentally) what you want, and so the test passes. You can follow this logic to see that it works for the second test as well.

The third and fourth tests are being passed objects with more than one key. { "a": 1, "b": 2 } is what’s passed in the third test.

var keys = Object.keys({ "a": 1, "b": 2 }); // ["a", "b"]
collection[i].hasOwnProperty(keys); // keys becomes "a,b", test fails.

What you want to do is iterate through the keys in source to make sure each key is present. It’s easy, just keep in mind that Object.keys returns an array.

1 Like