简体   繁体   中英

Validate if an object is not in array of object and throw in js

I have an object to validate if any from an array of object is not the same

const obj = {
    question: "What is your dog name?",
  answer: "Browny"
}

const array = [
  {
    question: "What is your name?",
    answer: "Diana"
  },
  {
    question: "What is your dog name?",
    answer: "Browny"
  }
]

I tried filtering and comparing them but it only check the first obj

array.filter(arr => {
  if (arr.question !== obj.question) response.status(409).json({message: 'Wrong question chosen'}) 
  if (arr.answer !== obj.answer) response.status(409).json({message: 'Please type the right answer'})

  else response.status(200)
})

I check on this JS: Filter array of objects by array, when object key is an array of objects but it got me kinda confusing

I hope you guys can help me, thanks in advance!

Ciao, you can follow this example:

 const obj = { question: "What is your dog name?", answer: "Browny" }; const array = [ { question: "What is your name?", answer: "Diana" }, { question: "What is your dog name?", answer: "Browny" } ]; let correct_answer = array.filter(el => el.question === obj.question)[0]; if (correct_answer.answer === obj.answer) console.log("correct answer"); else console.log("wrong answer");

So your code becomes:

let correct_answer = array.filter(arr => arr.question === obj.question);

if (correct_answer.length === 0) response.status(409).json({message: 'Wrong question chosen'}) 
else {
   if (correct_answer[0].answer === obj.answer) response.status(200);
   else response.status(409).json({message: 'Please type the right answer'});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM