为了账号安全,请及时绑定邮箱和手机立即绑定

验证对象是否不在对象数组中并抛出js

验证对象是否不在对象数组中并抛出js

潇潇雨雨 2022-12-22 09:58:38
我有一个对象来验证对象数组中的任何对象是否不相同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"  }]我尝试过滤和比较它们,但它只检查第一个对象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)})我检查了这个JS: Filter array of objects by array, when object key is an array of objects但它让我有点困惑我希望你们能帮助我,在此先感谢!
查看完整描述

1 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

再见,你可以按照这个例子:


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");

所以你的代码变成:


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'});

}


查看完整回答
反对 回复 2022-12-22
  • 1 回答
  • 0 关注
  • 50 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信