Home > Software design >  How to check if string matches any of the strings in the database
How to check if string matches any of the strings in the database

Time:11-01

I'm trying to check if string matches any of the strings saved in database, but with the code I have right now it checks only the first one My code:

for (const key in keys) {
  if (keys[key].key !== hashedQueryKey) {
    return "Invalid Key provided.";
  } else return true;
}

CodePudding user response:

You should not return if the key does not match as you want to continue comparing keys. Something like:

function queryMatches(keys, hashedQueryKey) {
 for (const key in keys) {
  if (keys[key].key === hashedQueryKey) {
    return true;
  }
 }
 return false;
}

CodePudding user response:

You could use Object.keys and Array.contains() to check if your key is present

if (Object.keys(keys).contains(hashedQueryKey)) {
    return true;
} else {
    return "Invalid Key provided.";
}

although looking at your code, and being paranoid ... just in case your 'key' property differs from the objects' key, using Object.keys and anyMatch() is safer ...

if (Object.keys(keys).anyMatch(key => keys[key].key === hashedQueryKey)) {
    return true;
} else {
    return "Invalid Key provided.";
}

if you don't need the message - just true or false , then you can just return the predicate.

ie.

return Object.keys(keys).contains(hashedQueryKey);
  • Related