如何将JSON嵌套对象聚合到其父对象的相邻下一位?
展开JSON数组中的嵌套disclosures对象并插入父对象后
需求说明
给定包含嵌套disclosures数组的JSON数组,需将每个父对象保留(移除disclosures属性),并将其disclosures中的每个对象依次插入到父对象的紧邻下一位,最终得到无嵌套的一维数组,且严格保持原顺序(父对象在前,对应嵌套对象紧随其后)。
原始JSON数组
[ { "questionText":"some text 1", "answerText":"some text" },{ "questionText":"some text 2", "answerText":"some text" },{ "questionText":"some text 3", "answerText":"some text", "disclosures":[ { "questionText":"some text 4", "answerText":"some text" },{ "questionText":"some text 5", "answerText":"some text" } ] },{ "questionText":"some text 6", "answerText":"some text" },{ "questionText":"some text 7", "answerText":"some text", "disclosures":[ { "questionText":"some text 8", "answerText":"some text" } ] } ]
目标JSON数组
[ { "questionText":"some text 1", "answerText":"some text" },{ "questionText":"some text 2", "answerText":"some text" },{ "questionText":"some text 3", "answerText":"some text" },{ "questionText":"some text 4", "answerText":"some text" },{ "questionText":"some text 5", "answerText":"some text" },{ "questionText":"some text 6", "answerText":"some text" },{ "questionText":"some text 7", "answerText":"some text" },{ "questionText":"some text 8", "answerText":"some text" } ]
解决方案
使用JavaScript的flatMap方法可以实现需求,它能遍历数组并将每个元素映射为新数组,最后自动展开为一维数组。具体逻辑如下:
- 遍历原始数组的每个元素;
- 对包含
disclosures的元素,先复制该元素并移除disclosures属性,再将处理后的父对象和disclosures中的所有对象组成新数组; - 对不包含
disclosures的元素,直接将其放入单元素数组; flatMap自动将所有子数组展开为最终的一维数组。
代码实现
const originalArray = [ {"questionText":"some text 1","answerText":"some text"}, {"questionText":"some text 2","answerText":"some text"}, {"questionText":"some text 3","answerText":"some text","disclosures":[{"questionText":"some text 4","answerText":"some text"},{"questionText":"some text 5","answerText":"some text"}]}, {"questionText":"some text 6","answerText":"some text"}, {"questionText":"some text 7","answerText":"some text","disclosures":[{"questionText":"some text 8","answerText":"some text"}]} ]; const transformedArray = originalArray.flatMap(item => { // 复制父对象并移除disclosures属性 const parentItem = {...item}; delete parentItem.disclosures; // 根据是否有disclosures返回对应数组 return item.disclosures ? [parentItem, ...item.disclosures] : [parentItem]; }); // 输出格式化后的结果 console.log(JSON.stringify(transformedArray, null, 3));
说明
- 该方法严格保持原顺序:父对象在前,其
disclosures中的对象按原顺序紧随其后; - 使用对象展开运算符
{...item}复制父对象,避免修改原始数据; flatMap替代普通map,解决了普通map会将嵌套数组保留在结果中的问题,自动完成数组展开。
内容的提问来源于stack exchange,提问作者mhery
相关产品推荐
相关产品推荐

