在JavaScript中如何将题目数组与答案数组关联匹配?
解决方案
你的代码有三个关键问题导致返回undefined:
- 属性名不匹配:answers数组里关联题目的字段是
questions_id,但你代码里写的是domanda_id,根本找不到匹配项 - map无返回值:当前map回调里只定义了temp变量,但没return任何内容,所以每个迭代默认返回undefined
- 错误使用find:如果一个题目对应多个答案,find只会返回第一个,应该用filter获取所有匹配的答案
修正后的代码如下:
const questions = [{ id: 1, text: 'question1' }, { id: 2, text: 'question2' }, { id: 3, text: 'question3' }]; const answers = [{ id: 1, text: 'answer1', questions_id: 1 }, { id: 2, text: 'answer2', questions_id: 1 }, { id: 3, text: 'answer3', questions_id: 2 }]; // 生成题目关联所有对应答案的新数组 const questionWithAnswers = questions.map(q => { const matchedAnswers = answers.filter(ans => ans.questions_id === q.id); // 保留原题目属性,新增answers字段存匹配到的答案 return { ...q, answers: matchedAnswers }; }); console.log(questionWithAnswers);
如果你的场景是每个题目只有一个对应答案,也可以用find,但要保证属性正确且有返回值:
const questionWithSingleAnswer = questions.map(q => { const matchedAnswer = answers.find(ans => ans.questions_id === q.id); return { ...q, answer: matchedAnswer || null // 无匹配时返回null,避免出现undefined }; });
内容的提问来源于stack exchange,提问作者Fabrizio Mastrone
相关产品推荐
相关产品推荐

