如何匹配嵌套对象与响应数组并统计选项出现次数?
问题描述
我拥有一个包含嵌套对象的questions对象:
const questions = { QID5: { choices: { 1: { choiceText: "Label 1" }, 2: { choiceText: "Label 2" }, 3: { choiceText: "Label 3" } } }, QID6: { choices: { 1: { choiceText: "English" }, 2: { choiceText: "French" } } } };
以及一个responses数组:
const responses = [ { labels: { QID5: ["Label 1", "Label 3"], QID6: ["English", "French"] } }, { labels: { QID5: ["Label 1"], QID6: ["English"] } }, { labels: { QID5: ["Label 2", "Label 3"], QID6: ["English"] } } ];
需要统计questions中每个选项在指定问题(QID)的所有响应中的出现次数,并将结果存入新对象的x、y数组属性中。例如QID5的期望结果为:
const desiredResult = { id: "QID5", x: ["Label 1", "Label 2", "Label 3"], y: [2, 1, 2] };
desiredResult.x中的Label 1在desiredResult.y中对应值为2(因为它出现在两个响应中),以此类推。
以下是我的尝试代码:
function getResults(id) { return responses.flatMap(response => response.labels[id]) } const arr = getResults("QID5"); const counts = {}; arr.forEach((x) => { counts[x] = (counts[x] || 0) + 1; }); const x = Object.keys(counts) const y = Object.values(counts) console.log(x) console.log(y)
解决方案
你的尝试完成了核心计数逻辑,但存在一个问题:生成的x数组只包含有响应的选项,无法保证和questions中该问题的选项顺序、完整性一致。要得到符合需求的结果,需要先从questions中获取指定QID的所有选项文本,再逐个统计它们在响应中的出现次数。
完整实现代码如下:
function getQuestionResult(qid) { // 获取指定问题的所有选项文本,保持原顺序 const questionChoices = questions[qid]?.choices; if (!questionChoices) { return { id: qid, x: [], y: [] }; } // 按选项的数字key排序,保证顺序和原问题一致 const sortedChoiceKeys = Object.keys(questionChoices).sort((a, b) => Number(a) - Number(b)); const x = sortedChoiceKeys.map(key => questionChoices[key].choiceText); // 初始化所有选项的计数为0 const counts = {}; x.forEach(label => counts[label] = 0); // 遍历所有响应,累加选项出现次数 responses.forEach(response => { const selectedLabels = response.labels[qid] || []; selectedLabels.forEach(label => { if (counts.hasOwnProperty(label)) { counts[label]++; } }); }); // 按x数组的顺序生成对应的y数组 const y = x.map(label => counts[label]); return { id: qid, x, y }; } // 测试QID5的结果 console.log(getQuestionResult("QID5")); // 输出:{ id: 'QID5', x: [ 'Label 1', 'Label 2', 'Label 3' ], y: [ 2, 1, 2 ] } // 测试QID6的结果 console.log(getQuestionResult("QID6")); // 输出:{ id: 'QID6', x: [ 'English', 'French' ], y: [ 3, 1 ] }
代码说明
- 提取选项:从
questions中取出指定QID的选项,通过排序数字key保证选项顺序和原问题一致,生成x数组。 - 初始化计数:为所有选项设置初始计数0,避免无响应的选项被遗漏。
- 累加计数:遍历每个响应的选中标签,对对应选项的计数进行累加。
- 生成结果数组:按照
x数组的顺序提取计数,确保x和y的索引一一对应。
内容的提问来源于stack exchange,提问作者psych0groov3
相关产品推荐
相关产品推荐

