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

如何遍历嵌套JSON数组,使用map渲染所有问题及对应答案内容

解决方案

是的,你需要额外嵌套map函数来遍历内层的questions数组,你当前代码中写的detail.questions[0]只会取每个分类下的第一个问题,无法展示所有嵌套条目。如果要按你要求渲染为表格格式,可以参考以下实现:

完整实现代码(兼容单/多答案场景)

<table>
  <thead>
    <tr>
      <th>分类</th>
      <th>问题</th>
      <th>答案</th>
    </tr>
  </thead>
  <tbody>
    {details.map((detail, detailIdx) => (
      // 遍历顶层分类数组
      detail.questions?.map((question, qIdx) => (
        // 遍历当前分类下的所有问题
        question.answers?.map((answer, aIdx) => (
          <tr key={`${detailIdx}-${qIdx}-${aIdx}`}>
            <td>{detail.name}</td>
            <td>{question.questionText}</td>
            <td>{answer.text}</td>
          </tr>
        )) ?? []
      )) ?? []
    ))}
  </tbody>
</table>

简化版本(确定每个问题仅一个答案时使用)

如果你的业务场景中每个问题固定只有一个答案,可以省略最内层的answers遍历,代码更简洁:

<table>
  <thead>
    <tr>
      <th>分类</th>
      <th>问题</th>
      <th>答案</th>
    </tr>
  </thead>
  <tbody>
    {details.map((detail, detailIdx) => (
      detail.questions?.map((question, qIdx) => (
        <tr key={`${detailIdx}-${qIdx}`}>
          <td>{detail.name}</td>
          <td>{question.questionText}</td>
          <td>{question.answers[0]?.text ?? ''}</td>
        </tr>
      )) ?? []
    ))}
  </tbody>
</table>

渲染效果

最终输出的表格内容如下:

分类问题答案
About YouWhat is your surname?Thomas
About YouWhere do you work?Finance
About FamilyChilderenYes
About FamilyMarriedNo
TravelDo you travel a lot?Yes

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 20:24:05