如何从多层嵌套的对象数组生成指定结构的简单对象数组
嵌套JSON转指定扁平对象数组实现方案
核心思路是逐层遍历嵌套的原始数据,将上层节点的学院、课程属性向下透传,和最内层学生节点的自有属性拼接为符合要求的对象,最终收集为目标数组。
具体实现步骤
- 第一步:获取并解析原始JSON数据
不管是通过接口请求还是本地读取,先把JSON格式的源数据转为JS可操作的普通对象,请求示例代码如下:async function loadSourceData() { // 替换为你自己的数据源地址 const resp = await fetch('你的JSON数据访问地址'); if (!resp.ok) throw new Error('数据加载失败'); return resp.json(); } - 第二步:编写核心转换逻辑
按照「学院 -> 课程 -> 学生」的层级逐层遍历,每一层记录当前节点需要的字段,到学生层级时组装为目标结构对象存入结果:function formatToTargetModel(source) { const result = []; // 遍历学院层级 source.institutes?.forEach(instituteItem => { const instituteName = instituteItem.name; // 替换为源数据里学院名称对应的实际字段 // 遍历当前学院下的课程 instituteItem.courses?.forEach(courseItem => { const courseName = courseItem.name; // 替换为源数据里课程名称对应的实际字段 // 遍历当前课程下的学生 courseItem.students?.forEach(studentItem => { result.push({ instituteName, courseName, studentFirstname: studentItem.firstname, studentSurname: studentItem.surname, appreciation: studentItem.appreciation, finalGrade: studentItem.finalGrade, behaviour: studentItem.behaviour, completenessOfStapler: studentItem.completenessOfStapler }) }) }) }) return result; } - 第三步:调用方法得到最终结果
async function run() { const sourceData = await loadSourceData(); const model = formatToTargetModel(sourceData); // 后续直接使用model数组即可 console.log(model); } run();
注意事项
如果你的源数据嵌套层级、字段命名和上述遍历逻辑不匹配,直接修改对应遍历的属性路径即可,核心逻辑不需要调整。代码中使用了可选链
?.做兼容,即使某一层级为空(比如某学院未关联课程、某课程没有学生数据)也不会抛出遍历报错。
内容的提问来源于stack exchange,提问作者Shamaz saeed
相关产品推荐
相关产品推荐

