按Key合并相同数据:将student_Info改为数组格式的技术求助
修正学生数据处理代码:按Key合并数据并将student_Info设为数组
原始学生数据
{ "entity": "student", "records": [ { "associatedStudentId": 111, "data": { "info":{ "position": 1, "id": 111 }, "entity":{ "id": 222 } } }, { "associatedStudentId": 222, "data": { "info":{ "position": 2, "id": 222 }, "entity":{ "id": 222 } } } ], "personalInfo": { "111":{ "Father_Name": "Amar" }, "222":{ "Father_Name": "Akbar" } } }
当前代码处理结果
[{ "key": 111, "student_Info": { }, "personal_Info":{ } }]
预期结果
[ { "key": 111, "student_Info": [ ], "personal_Info":{ } }]
尝试的代码
let rawdata = fs.readFileSync('./student_data.json'); let data = JSON.parse(rawdata); let tempStudents=[] let tempInfo=[] let students = jmespath.search(data,"records[*].{key: associatedStudentId, student_Info:data}") students.forEach((element, value) => { tempStudents.push(element) }); let info = jmespath.search(data,"values(personal_Info)[*].{key: entity.id, value: @}") info.forEach((element, value) => { tempInfo.push(element) }); student_data=tempInfo.concat(tempStudents) const res = Object.values(student_data.reduce((acc,{name,...rest}) => { acc[name]??={name} acc[name] = {...acc[name],...rest} return acc },{})) console.log(res)
修正后的代码
const fs = require('fs'); const jmespath = require('jmespath'); let rawdata = fs.readFileSync('./student_data.json'); let data = JSON.parse(rawdata); // 处理学生记录,将student_Info初始化为数组格式 let students = jmespath.search(data, "records[*].{key: associatedStudentId, student_Info: [data]}"); // 处理个人信息,匹配对应studentId并设置personal_Info字段 let personalInfos = Object.entries(data.personalInfo).map(([key, value]) => ({ key: parseInt(key), personal_Info: value })); // 合并数据并按key分组,维护student_Info的数组结构 const merged = [...students, ...personalInfos].reduce((acc, item) => { const { key, ...rest } = item; // 初始化当前key的基础结构 if (!acc[key]) { acc[key] = { key, student_Info: [], personal_Info: {} }; } // 追加student_Info数组元素 if (rest.student_Info) { acc[key].student_Info.push(...rest.student_Info); } // 合并个人信息 if (rest.personal_Info) { acc[key].personal_Info = { ...acc[key].personal_Info, ...rest.personal_Info }; } return acc; }, {}); // 转换为数组格式输出 const res = Object.values(merged); console.log(JSON.stringify(res, null, 2));
修正说明
- student_Info数组初始化:提取学生记录时,直接用
[data]将单个data对象包装成数组,确保字段从一开始就是数组类型。 - 个人信息处理修正:原代码的jmespath查询逻辑错误,改用
Object.entries遍历personalInfo,直接将键转为数字类型的studentId,同时指定personal_Info字段。 - 合并逻辑优化:
- 初始化每个key的条目时,明确设置
student_Info为空数组、personal_Info为空对象,保证结构符合预期。 - 合并时,用
push(...rest.student_Info)追加数组元素,保留数组格式;个人信息直接合并对象。
- 初始化每个key的条目时,明确设置
- 冗余代码移除:删除了不必要的临时数组,直接使用处理后的结果进行合并。
内容的提问来源于stack exchange,提问作者coder
相关产品推荐
相关产品推荐

