Angular中如何实现行转列与列转行的数据转换
Angular 数据行转列与列转行实现方案
一、行转列(长表转宽表)
需求说明
将按比赛拆分的球员得分长表,转换为以球员为维度、各比赛得分为字段的宽表,并计算总分。
原始数据示例
const rawData = [ {"playerId": "1001","playerName": "Lebron James","game": "Game1","score": 35}, {"playerId": "1001","playerName": "Lebron James","game": "Game2","score": 40}, {"playerId": "1001","playerName": "Lebron James","game": "Game3","score": 38}, {"playerId": "1001","playerName": "Lebron James","game": "Game4","score": 25}, {"playerId": "1002","playerName": "Anthony Davis","game": "Game1","score": 18}, {"playerId": "1002","playerName": "Anthony Davis","game": "Game2","score": 12}, {"playerId": "1002","playerName": "Anthony Davis","game": "Game3","score": 7}, {"playerId": "1002","playerName": "Anthony Davis","game": "Game4","score": 17} ];
转换后目标数据
const transformedData = [ {"playerId": "1001","playerName": "Lebron James","Game1": 35,"Game2": 40,"Game3": 38,"Game4": 25,"total": 138}, {"playerId": "1002","playerName": "Anthony Davis","Game1": 18,"Game2": 12,"Game3": 7,"Game4": 17,"total": 54} ];
实现函数
function pivotRowsToColumns(rawData: any[]): any[] { // 按playerId分组聚合数据 const grouped = rawData.reduce((acc, item) => { const key = item.playerId; if (!acc[key]) { acc[key] = { playerId: item.playerId, playerName: item.playerName, total: 0 }; } // 将game作为属性名,score作为属性值 acc[key][item.game] = item.score; // 累加总分 acc[key].total += item.score; return acc; }, {}); // 将对象转换为数组返回 return Object.values(grouped); } // 调用示例 const pivotedData = pivotRowsToColumns(rawData);
二、列转行(宽表转长表)
需求说明
将转换后的宽表,重新拆分为原始的按比赛拆分的长表格式。
实现函数
function pivotColumnsToRows(pivotedData: any[]): any[] { const result: any[] = []; // 遍历每个球员的宽表数据 pivotedData.forEach(player => { // 提取非比赛字段 const { playerId, playerName, total, ...games } = player; // 遍历每个比赛字段,生成原始格式的行数据 Object.entries(games).forEach(([game, score]) => { result.push({ playerId, playerName, game, score }); }); }); return result; } // 调用示例 const restoredData = pivotColumnsToRows(pivotedData);
核心思路
- 行转列:用
reduce按playerId分组,把动态的game字段转为对象属性,同时累加计算总分,最后将分组对象转为数组。 - 列转行:通过解构分离固定字段与比赛字段,遍历比赛字段生成原始结构的数组元素。
- Angular适配:可将两个函数封装为
DataTransformService服务,在组件中注入调用,适配不同业务场景的数据转换需求。
内容的提问来源于stack exchange,提问作者njel2003
相关产品推荐
相关产品推荐

