Wherefore art thou javascript challenges

Tell us what’s happening:
My code is passing the first three tests but not the rest. I’m not taking into account that the source object might have more than one key. So far I feel that my code is a bit flaky, like there is a more functional way of doing it. Should I be reviewing how to refer to the keys and values inside objects better? Should I be comparing the keys in the source object to the keys in the collection object and not the other way around?

Your code so far


function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];

  for(let obj of collection){
    for(let key of Object.keys(obj)){
      if(key === Object.keys(source)[0]){
        if(obj[key] === source[key]){
          arr.push(obj);
        }
      }
    }
  }
  // Only change code above this line
  return arr;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou

1.compare source to each object in collection
2.if object in collection contains source { push object to array [] }

*if object does not contain all items in source { ignore }

tips:
use console.log in in your function so you can see what your function does while you build it in codepen

dont nest if statements inside other if statements. use && instead. eg if (obj === true && obj[key] == 1){do a thing}. makes it way easier to read and understand

I get the basics of what your saying but since I am trying to compare objects it makes it more difficult. I don’t how to extract the keys for comparison (seeing whether collection contains the said key and also the associated value).

function whatIsInAName(collection, object) {
    var passValue = Object.keys(object).length;
    var counter = 0;
    var correctObjects = [];
    for (var i = 0; i < collection.length; i++) {
        var currentObject = collection[i];
        counter = 0

        for (var key in currentObject) {
            var currentValue = currentObject[key];
            if (object[key] === currentValue) {
                counter++;
            }
        }

        if (counter === passValue) {
            correctObjects.push(currentObject);
        }
    }

    return correctObjects;
}

Thanks,
sailaja
MSBI Developer