如何按ID嵌套合并对象:将answerText嵌入对应answers
多层嵌套数据结构实现方案
我需要处理从API获取的结构化数据,已经实现将answers基于questionId嵌入对应questions中,现在要进一步把answerText基于answerId嵌入对应answers,形成多层嵌套的目标结构。
初始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" } ], "answerText":[ { "id":1, "answerId":1, "text":"Some text" }, { "id":2, "answerId":2, "text":"Some text" }, { "id":3, "answerId":3, "text":"Some text" } ] }
已实现的代码
const newItem = data.questions.map((t1) => ({ ...t1, answers: data.answers.filter((t2) => t2.questionId === t1.id), }));
目标数据结构
{ "questions":[ { "id":1, "questionHeader":"Some question header", "questionText":"Some question text?", "answers":[ { "id":1, "questionId":1, "answer":"Some answer", "answerText":[ { "id":1, "answerId":1, "text":"Some text" } ] }, { "id":2, "questionId":1, "answer":"Some answer", "answerText":[ { "id":2, "answerId":2, "text":"Some text" } ] } ] }, { "id":2, "questionHeader":"Some question header", "questionText":"Some question text?", "answers":[ { "id":3, "questionId":2, "answer":"Some answer", "answerText":[ { "id":3, "answerId":3, "text":"Some text" } ] } ] } ] }
实现方案
只需要在原来处理answers的逻辑里,对每个匹配的answer再做一次映射,添加对应的answerText即可。如果数据量较大,建议先把answerText转成以answerId为键的Map,提升查找效率。
基础实现(直接嵌套filter)
const newItem = data.questions.map((question) => ({ ...question, answers: data.answers // 先筛选当前question对应的answers .filter(answer => answer.questionId === question.id) // 给每个answer添加对应的answerText .map(answer => ({ ...answer, answerText: data.answerText.filter(text => text.answerId === answer.id) })) }));
优化实现(用Map提升性能)
// 先将answerText转为Map,key是answerId,value是对应的text对象 const answerTextMap = new Map(data.answerText.map(text => [text.answerId, text])); const newItem = data.questions.map((question) => ({ ...question, answers: data.answers .filter(answer => answer.questionId === question.id) .map(answer => ({ ...answer, // 因为示例中每个answer对应一个answerText,所以用[]包裹成数组 answerText: [answerTextMap.get(answer.id)] })) }));
两种方案都能得到目标结构,优化方案在数据量大时性能更优,避免了多次遍历answerText数组。
内容的提问来源于stack exchange,提问作者TTBox
相关产品推荐
相关产品推荐

