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

求助:如何整理含同名对象数组的调查数据及结果页展示

解决调查结果数据解构与展示问题

为什么totalAnswers.length返回undefined?

你给出的数据结构外层是对象,totalAnswers是这个对象的一个属性,其值才是数组。比如你的数据实际结构为:

const surveyData = {
  totalAnswers: [
    { answers: [answer0, answer1, answer2, answer3] },
    { answers: [...] },
    // ...更多回答对象
  ]
};

如果你直接调用totalAnswers.length,相当于误把外层对象当成了totalAnswers数组,正确做法是先获取对象里的数组:

// 拿到真正的回答数组
const answersArray = surveyData.totalAnswers;
// 现在就能正常获取长度
console.log(answersArray.length); // 输出回答的总数量

解构数据并按问题展示

要让调查创建者查看每个问题的所有答案,核心是把所有回答中对应位置的答案分组(即第1个问题的所有回答、第2个问题的所有回答...),具体步骤如下:

1. 按问题分组答案

先提取所有回答里的answers数组,再按问题索引聚合:

const answersArray = surveyData.totalAnswers;
// 确定调查的问题数量(取第一个回答的答案长度,假设所有回答的问题数一致)
const questionCount = answersArray[0]?.answers.length || 0;

// 生成按问题分组的答案数组
const groupedByQuestion = Array.from({ length: questionCount }, (_, questionIdx) => {
  // 收集所有回答中第questionIdx个问题的答案
  return answersArray.map(answerObj => answerObj.answers[questionIdx]);
});

最终groupedByQuestion的结构为:

[
  [问题1的所有答案],
  [问题2的所有答案],
  // ...对应每个问题的答案数组
]

2. 在DOM中展示结果

遍历分组后的数组,为每个问题创建独立展示区块,包含原始答案列表和统计信息:

<!-- 提前在HTML中准备结果容器 -->
<div id="survey-results"></div>
const resultsContainer = document.getElementById('survey-results');

groupedByQuestion.forEach((questionAnswers, index) => {
  // 创建问题容器
  const questionBlock = document.createElement('div');
  questionBlock.style.marginBottom = '2rem';
  
  // 问题标题
  const questionTitle = document.createElement('h3');
  questionTitle.textContent = `问题 ${index + 1}`;
  questionBlock.appendChild(questionTitle);
  
  // 原始答案列表
  const answerList = document.createElement('ul');
  questionAnswers.forEach(answer => {
    const li = document.createElement('li');
    li.textContent = answer;
    answerList.appendChild(li);
  });
  questionBlock.appendChild(answerList);
  
  // 答案统计(次数+占比)
  const stats = document.createElement('div');
  stats.style.marginTop = '1rem';
  const countMap = {};
  
  questionAnswers.forEach(ans => {
    countMap[ans] = (countMap[ans] || 0) + 1;
  });
  
  Object.entries(countMap).forEach(([ans, count]) => {
    const percentage = ((count / questionAnswers.length) * 100).toFixed(1);
    const statItem = document.createElement('p');
    statItem.textContent = `${ans}:${count} 次(${percentage}%)`;
    stats.appendChild(statItem);
  });
  
  questionBlock.appendChild(stats);
  resultsContainer.appendChild(questionBlock);
});

3. 额外优化建议

  • 如果调查包含问题文本(如每个问题的标题),可以将问题文本与分组后的答案对应,展示更清晰
  • 对于选择题类型,可通过柱状图、饼图等可视化方式展示统计结果,提升可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 02:30:52