如何使用JavaScript的.find()方法查找嵌套结构中匹配指定questionId的项?
解决.find()方法匹配嵌套数据结构的问题
嘿,这问题其实很容易修正!你之前的写法出错是因为找错了questionId的位置——它根本不在answers子数组里,而是直接属于外层数组的每个对象。
错误原因分析
你原来的代码:
answers.find(question => question.answers.questionId === displayingQuestionId)
这里的question.answers是一个数组,数组本身没有questionId属性,所以肯定匹配不到任何结果。
正确写法
直接访问外层对象的questionId属性就可以了:
const matchedQuestion = answers.find(question => question.questionId === displayingQuestionId);
这样find()会遍历answers数组里的每一项,找到第一个questionId和displayingQuestionId相等的对象。
额外扩展:获取匹配项的答案列表
如果找到匹配项后,你想拿到对应的答案数组,可以这样做:
const matchedQuestion = answers.find(question => question.questionId === displayingQuestionId); if (matchedQuestion) { // 这里就能拿到该问题对应的所有答案 const targetAnswers = matchedQuestion.answers; console.log('找到的答案:', targetAnswers); } else { console.log('没有找到匹配的问题'); }
内容的提问来源于stack exchange,提问作者The Walrus
相关产品推荐
相关产品推荐

