後端返回長表格式數據(行數據),前端圖表庫(如 ECharts、Highcharts)需寬表格式(列數據)。需將:
// 源數據(長格式)
[
{ month: '201201', city: '鄭州', metric: '電量', value: 33 },
{ month: '201201', city: '新鄉', metric: '電量', value: 29 },
{ month: '201201', city: '安陽', metric: '電量', value: 23 },
...
]
// 目標數據(寬格式)
[
{ month: '201201', '鄭州-電量': 33, '新鄉-電量': 29, '安陽-電量': 23 },
{ month: '201202', '鄭州-電量': 35, '新鄉-電量': 26, '安陽-電量': 25 },
...
]
/**
* JSON 數據行轉列(透視表轉換)
* @param {Array} data - 源數據數組
* @param {String} idField - 主鍵字段(如 'month')
* @param {String} fromFields - 要轉為列的字段,逗號分隔(如 'city,metric')
* @param {String} toField - 作為列名前綴的字段(如 'city')
* @returns {Array} 轉換後的數據
*/
function pivotData(data, idField, fromFields, toField) {
const result = [];
const fromFieldArr = fromFields.split(',');
const idMap = new Map(); // idField 值 -> 結果索引
data.forEach(row => {
const idVal = row[idField];
let targetRow;
// 查找或創建目標行
if (idMap.has(idVal)) {
targetRow = result[idMap.get(idVal)];
} else {
targetRow = { [idField]: idVal };
idMap.set(idVal, result.length);
result.push(targetRow);
}
// 處理轉換字段
fromFieldArr.forEach(field => {
const colName = `${row[toField]}-${row[field]}`;
targetRow[colName] = row[field];
});
});
return result;
}
const sourceData = [
{ yearmonth: 201201, ppq: 23, spq: 27, company: 'dfsoft' },
{ yearmonth: 201202, ppq: 33, spq: 38, company: 'dfsoft' },
{ yearmonth: 201201, ppq: 29, spq: 26, company: 'vcom' },
{ yearmonth: 201202, ppq: 34, spq: 38, company: 'vcom' }
];
const result = pivotData(sourceData, 'yearmonth', 'ppq,spq', 'company');
/* 結果:
[
{ yearmonth: 201201, 'dfsoft-ppq': 23, 'dfsoft-spq': 27, 'vcom-ppq': 29, 'vcom-spq': 26 },
{ yearmonth: 201202, 'dfsoft-ppq': 33, 'dfsoft-spq': 38, 'vcom-ppq': 34, 'vcom-spq': 38 }
]
*/
function unpivotData(data, idField, valuePrefix) {
const result = [];
data.forEach(row => {
Object.keys(row).forEach(key => {
if (key === idField) return;
if (!valuePrefix || key.startsWith(valuePrefix)) {
const [category, metric] = key.split('-');
result.push({
[idField]: row[idField],
category,
metric,
value: row[key]
});
}
});
});
return result;
}
Map 替代 findIndex 降低複雜度至 O(n)