如何将JavaScript嵌套问卷对象转换为含answer、comments的目标结构?
问题原因
你初始声明的jsonObj是数组类型,所有生成的条目都被直接推到了顶层数组里,自然会得到扁平化的结果。目标结构是和原数据结构一致的嵌套对象,你需要保留原对象的所有键名,每个键对应处理后的子数组。
修改后的代码
const questions_chklist = { credit_broker_checklist: [ { id: '1', title: 'Are any identified risks to the customer given equal prominence?', question_id: 'wmBHr' } , { id: '2', title: 'Content has been approved by an authorised individual', question_id: 'sPYvu' } , { id: '3', title: 'Does it clearly name your company or the ?', question_id: '64bBL' } ] , test_checklist_checklist: [ { id: '1', title: 'new questionn 1', question_id: '0VsnL' } , { id: '2', title: 'new question 02', question_id: 'c9jrW' } , { id: '3', title: 'New question 03', question_id: 'fbJON' } , { id: '4', title: 'new question 412234', question_id: 'AbcDE' } ] , new_list_checklist: [ ] } // 初始化为对象,不是数组 let jsonObj = {} for (var key in questions_chklist) { if (questions_chklist.hasOwnProperty(key)) { // 给当前键初始化空数组 jsonObj[key] = [] let option_count = questions_chklist[key].length; for (let i = 0; i < option_count; i++) { let item = {} item.answer = ""; item.comments = ""; item.question_id = questions_chklist[key][i].question_id // 推到当前键对应的数组里,不是顶层对象 jsonObj[key].push(item); } } } console.log(jsonObj)
更简洁的现代JS写法
你也可以用Object.entries + map 组合实现,代码更简洁易读:
const result = Object.fromEntries( Object.entries(questions_chklist).map(([key, list]) => [ key, list.map(item => ({ answer: '', comments: '', question_id: item.question_id })) ]) ) console.log(result)
内容的提问来源于stack exchange,提问作者Jerome Taylor
相关产品推荐
相关产品推荐

