Search code examples
javascriptobjectnestedreturn

Can't Retrieve Nested Return Values


The goal of my current algorithm challenge is to confirm the truthity of the second value of the evaluated obj with the given key (second arg). I know the simpler way to do it is using the Array.every, but I wanted to try to break it into steps for myself.

For whatever reason, I am unable to break out of the function and return false when meeting the conditions that the key is incorrect or the value associated with the key is falsy. It simply returns undefined. I'm used to iterations more from a Ruby perspective, so I don't know if that is skewing my perception of how this should work.

Thanks in advance. Here's my code:

function truthCheck(collection, pre) {
  collection.forEach((obj) =>{
    let key = Object.keys(obj)[1];
    if (!(key === pre)){
      console.log("no matching key")
     return false;
    }else if (key === pre){
      if(!obj[pre]){
        console.log("falsey value")
        return false;
      }
      }
    }
  )
 return true;
}

console.log(truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex"));

Solution

  • forEach doesn't have a way for you to cut the loop short. If you want to do that, you have a few options:

    • Use for-of (or for) and break
    • Use some and return true when you want to stop
    • Use every and return false when you wan to stop

    In your case, since you're looping through object keys, you might use for-in (and a hasOwnProperty check if appropriate) and break.

    My answer to For each over array in JavaScript lists various ways to loop, including the above, with examples.