如何将含数组类型键的对象转换为无数组键的拆解对象
如何将学生列表按地址与爱好的笛卡尔积展开转换结构
问题描述
现有一个学生列表数据,每个学生对象包含address(地址数组)和hobbies(爱好数组)字段,需要将数据转换为以下结构:
- 每个条目对应单个地址 + 单个爱好的组合;
- 移除原
address数组,替换为地址对象中的location和building字段; - 将原
hobbies数组改为单个爱好对象。
原始数据结构
const studentsList = { students: [ { id: '54654', name: 'Tony', address: [ { location: 'SNG', building: 2, }, { location: 'LON', building: 3, }, ], hobbies: [ { name: 'soccer', id: 123, }, { name: 'music', id: 53, }, ], }, { id: '505389', name: 'Stephen Strange', address: [ { location: 'LUX', building: 8, }, { location: 'HK', building: 25, }, ], hobbies: [ { name: 'watch tv', id: 143, }, { name: 'music', id: 83, }, ], }, { id: '34534389', name: 'Wanda Maximoff', address: [ { location: 'HKG', building: 89, }, { location: 'GEN', building: 79, }, ], hobbies: [ { name: 'reading', id: 45, }, { name: 'chess', id: 37, }, ], }, ], }
目标数据结构
const studentsList = { students: [ { id: '54654', name: 'Tony', location: 'SNG', building: 2, hobbies: { name: 'soccer', id: 123, }, }, { id: '54654', name: 'Tony', location: 'LON', building: 3, hobbies: { name: 'soccer', id: 123, }, }, { id: '54654', name: 'Tony', location: 'SNG', building: 2, hobbies: { name: 'music', id: 53, }, }, { id: '54654', name: 'Tony', location: 'LON', building: 3, hobbies: { name: 'music', id: 53, }, }, { id: '505389', name: 'Stephen Strange', location: 'LUX', building: 8, hobbies: { name: 'watch tv', id: 143, }, }, { id: '505389', name: 'Stephen Strange', location: 'HK', building: 25, hobbies: { name: 'watch tv', id: 143, }, }, { id: '505389', name: 'Stephen Strange', location: 'HK', building: 25, hobbies: { name: 'music', id: 83, }, }, { id: '505389', name: 'Stephen Strange', location: 'LUX', building: 8, hobbies: { name: 'music', id: 83, }, }, { id: '34534389', name: 'Wanda Maximoff', location: 'HKG', building: 89, hobbies:{ name: 'reading', id: 45, }, }, { id: '34534389', name: 'Wanda Maximoff', location: 'GEN', building: 79, hobbies:{ name: 'reading', id: 45, }, }, { id: '34534389', name: 'Wanda Maximoff', location: 'HKG', building: 89, hobbies:{ name: 'chess', id: 37, }, }, { id: '34534389', name: 'Wanda Maximoff', location: 'GEN', building: 79, hobbies:{ name: 'chess', id: 37, }, } ], }
解决方案代码
通过嵌套的flatMap和map实现地址与爱好的笛卡尔积展开,代码如下:
// 原始数据 const studentsList = { students: [ // 放入上述原始学生数据 ], }; // 执行转换 const transformedList = { students: studentsList.students.flatMap(student => { // 遍历每个地址,再遍历每个爱好,生成组合条目 return student.address.flatMap(addr => { return student.hobbies.map(hobby => ({ id: student.id, name: student.name, location: addr.location, building: addr.building, hobbies: hobby })); }); }) }; // 输出结果 console.log(transformedList);
代码说明
- 外层
flatMap遍历所有学生,确保每个学生展开后的条目被扁平化到同一数组; - 内层
flatMap遍历当前学生的每个地址; - 最内层
map遍历当前学生的每个爱好,将学生基础信息、地址字段、单个爱好组合成新对象; - 最终生成的数组完全匹配目标结构,每个条目对应一组地址与爱好的组合。
内容的提问来源于stack exchange,提问作者user21357723
相关产品推荐
相关产品推荐

