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

如何按questionId分组测验对象数组,实现同问题下多答案聚合渲染

解决方案

首先你需要先对原始测验数组做预处理,按questionId分组,把同一题的所有答案聚合存储:

const groupedQuiz = quizData.reduce((acc, curr) => {
  if (!acc[curr.questionId]) {
    acc[curr.questionId] = {
      questionId: curr.questionId,
      question: curr.question,
      questiontype: curr.questiontype,
      userId: curr.userId,
      answers: []
    }
  }
  acc[curr.questionId].answers.push(curr.answer)
  return acc
}, {})

// 转为数组方便后续遍历渲染
const processedQuizList = Object.values(groupedQuiz)

之后直接渲染处理后的聚合数组即可,外层遍历题目,内层遍历当前题的所有答案:

{processedQuizList.map((item) => {
  return (
    <div key={item.questionId}>
      <Col xs={12}>
        <p className="text-start quiz-text">
          <strong>
            Question {item.question}
          </strong>
        </p>
      </Col>
      <Col xs={12}>
        {item.answers.map((answer, ansIdx) => (
          <p key={ansIdx} className="text-start argent c-font quiz-text">{answer}</p>
        ))}
      </Col>
    </div>
  );
})}

补充说明:

  • 建议用questionId作为外层遍历的key,比索引index稳定性更高,避免数组顺序变动导致的渲染异常
  • 你示例中questionId=14的两条数据题面不一致属于异常情况,如果实际业务中存在同id不同题面的场景,可以自行调整分组逻辑,比如优先取第一条出现的题面即可

内容的提问来源于stack exchange,提问作者TTBox

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:06:02