Need some insight in this code (Object/keys iteration)

I´ve been battling with this challenge since I can´t remember how long:

Today I tried, once again. And I´ve came up with this approach that I´m pretty happy, the bad thing is that the cody only works if the source array has only one item to compare. That´s why I have separate the code into 2 If statements. Now I´m having difficulty developing the second if statement (the one which is commented out)

function whatIsInAName(collection, source) {

  // If Object.keys(source) is just 1 item:
      if (source[Object.keys(source)] != undefined){
          let nameinSource = source[Object.keys(source)]
          let keyinSource = Object.keys(source)
          // 1.Use filter on first array
          return collection.filter(obj => obj.hasOwnProperty(Object.keys(source)) && (obj[keyinSource] === nameinSource)
  else {
    let keyslength = (Object.keys(source).length)
    let keysinSource = []
        for (let i=0; i<keyslength;i++){

When source has several items everything seems to complicate a lot. First I have to save in an array each keys, properties etc, then I have to loop etc. Is this wise or I should re-consider what I´m doing? If I have to re-consider it will be probably the 20th time lol but anyway, I´ll probably finish all FCC curriculum before I finish this dman challenge :smile:

So I would rethink this. So first, if you have two objects, how would you check that objectA contains all the keys in objectB, and if it does, are the values the same?

  • Object.keys(objectB) gives you an array of keys.
  • You can loop over those keys (either imperative loop, or you can use an array method like every).
  • key in objectA will return true or false
  • if it returns true, is objectA[key] === objectB[key]
  • if yes, return objectA

Once you can do that with one, you can just loop through the array of object (objectsAcollection in the function) and run the above for each one – you can either have an empty array, then imperatively loop over and push to that array, or you can use an array method like map or similar.

1 Like

I just did it how you tell me and I solved in 10 minutes lol… I guess sometimes one just can´t do it alone.