You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:25:42