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

如何根据ID合并API返回的问答对象数组?

问题:将API返回的问答数据关联重组结构

API返回的数据结构如下:

{"questions":[{"id":1,"questionHeader":"Some question header","questionText":"Some question text?"},{"id":2,"questionHeader":"Some question header","questionText":"Some question text?"}],"answers":[{"id":1,"questionId":1,"answer":"Some answer"},{"id":2,"questionId":1,"answer":"Some answer"},{"id":3,"questionId":2,"answer":"Some answer"}]}

需要将每个问题对应的所有答案嵌入到问题对象中,形成每个question包含answers数组的目标结构:

{"questions":[{"id":1,"questionHeader":"Some question header","questionText":"Some question text?","answers":[{"id":1,"questionId":1,"answer":"Some answer"},{"id":2,"questionId":1,"answer":"Some answer"}]},{"id":2,"questionHeader":"Some question header","questionText":"Some question text?","answers":[{"id":3,"questionId":2,"answer":"Some answer"}]}]}

当前代码只能为每个问题添加单个答案,无法生成答案数组:

const newItem = data.questions.map((t1) => ({...t1,...data.answers.find((t2) => t2.questionId === t1.id),}));console.log(newItem);

解决方案

你当前代码使用的find方法只会返回第一个匹配的答案,要获取所有对应答案,改用filter方法筛选出所有匹配项,并为每个问题添加answers属性:

const newItem = data.questions.map(question => ({
  ...question,
  answers: data.answers.filter(answer => answer.questionId === question.id)
}));
console.log(newItem);

代码说明

  • 用map遍历每个问题对象,通过展开运算符...question复制原问题的所有属性
  • 新增answers属性,值为通过filter筛选出的、所有questionId与当前问题id匹配的答案数组,这样就能得到每个问题对应的全部答案

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:27:22