简体   繁体   English

如何检查元素是否存在于数组对象中

[英]How to check if an element exists within an object of arrays

I'm trying to check if an array within an object contains an element userAnswer or not. 我正在尝试检查对象内的数组是否包含元素userAnswer Is there a good way to do this using es6. 是否有使用es6做到这一点的好方法。 I've tried a few however, I can't seem to get it to work properly. 我尝试了一些,但是似乎无法正常工作。 Most of my attempts return an error. 我的大多数尝试都返回错误。 Any help would be appreciated. 任何帮助,将不胜感激。

Last Attempt 最后一次尝试

conductedExam.questions.some(question => question.userAnswer.includes(Object))

Data 数据

{
  _id: '1',
  questions: [
    { name: '1', userAnswer: 'one' },
    { name: '2', userAnswer: 'two' },
    { name: '2' }
  ]
};

Use hasOwnProperty : 使用hasOwnProperty

 const conductedExam = { _id: '1', questions: [ { name: '1', userAnswer: 'one' }, { name: '2', userAnswer: 'two' }, { name: '2' } ] }; console.log(conductedExam.questions.some(e => !e.hasOwnProperty("userAnswer"))); 

Using hasOwnProperty might work. 使用hasOwnProperty可能有效。

conductedExam.questions.some(question => question.hasOwnProperty('userAnswer')) returns true conductedExam.questions.some(question => question.hasOwnProperty('userAnswer'))返回true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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