首页 > 解决方案 > how deep can .find go

问题描述

I know I can use find easily like

answers.find(question => question.questionId === displayingQuestionId)

but my structure is:

answers: [
  {questionId: 0000,
   answers: [{title: 'answer1'},{title: 'answer2'}]
]

so how can I use find in this:

where I want to find the questionId that matches the questionId for the answers

I realise this is quite confusing

answers.find(question => question.answers.questionId === displayingQuestionId)

something like that ^ except that is not working...

标签: javascriptarraysreactjsfind

解决方案


所以基本上你可以得到你想要的深度。但是您不能只使用 question.answers.questionId 进行正确比较。显然, .find 的每个循环都会为您提供顶级对象。之后,您可以随心所欲地做这一切。

例子:

let arr = [{'questionId': 0000, 'answers': [{'title': 'answer1'},{'title': 'answer2'}]}];

//returns object of the top level if questioned equals to 0

arr.find((answer) => answer.questionId === 0);

//comparison with the internal array elements
//returns answer if one of the internal answers has title 'answer 1'

arr.find((answer) => !!answer.answers.find((internalAnswer => internalAnswer.title === 'answer1')));

推荐阅读