echarts多個折線案例
var data = [
{"date":"2023-06-11","method":"","total":"9"},
{"date":"2023-06-12","method":"","total":"73"},
{"date":"2023-06-13","method":"","total":"107"},
{"date":"2023-06-13","method":"article","total":"10"},
{"date":"2023-06-13","method":"home","total":"9"},
{"date":"2023-06-14","method":"article","total":"27"},
{"date":"2023-06-14","method":"home","total":"93"},
{"date":"2023-06-15","method":"article","total":"4"},
{"date":"2023-06-15","method":"home","total":"67"},
{"date":"2023-06-16","method":"article","total":"17"},
{"date":"2023-06-16","method":"home","total":"83"},
{"date":"2023-06-17","method":"article","total":"2"},
{"date":"2023-06-17","method":"home","total":"61"},
{"date":"2023-06-18","method":"home","total":"35"}
];
// 使用對象字面量創(chuàng)建 totalsByMethod 對象,將日期和方法作為鍵铁追,總數(shù)作為值
var totalsByMethod = {};
data.forEach(item => {
var date = item.date;
var method = item.method;
var total = parseInt(item.total);
if (!totalsByMethod[date]) {
totalsByMethod[date] = {};
}
totalsByMethod[date][method] = total;
});
// 獲取日期數(shù)組和方法數(shù)組
var xAxisData = Object.keys(totalsByMethod);
var methodArray = Array.from(new Set(data.map(item => item.method)));
// 創(chuàng)建 seriesData 數(shù)組路翻,存儲各個方法的數(shù)據(jù)
var seriesData = methodArray.map(method => {
return {
name: method,
type: 'line',
data: xAxisData.map(date => totalsByMethod[date][method] || 0)
};
});
// 創(chuàng)建 ECharts 實例并配置選項
var chart = echarts.init(document.getElementById('chart-container'));
var options = {
xAxis: {
type: 'category',
data: xAxisData
},
yAxis: {
type: 'value'
},
series: seriesData
};
chart.setOption(options);
優(yōu)化部分的說明:
使用對象字面量創(chuàng)建
totalsByMethod 對象同廉,并直接將日期和方法作為鍵币狠,總數(shù)作為值抄课,避免了后續(xù)的判斷和多次訪問對象屬性厢破。
使用
Object.keys(totalsByMethod) 獲取日期數(shù)組峭沦,而不是使用原始數(shù)據(jù)進行遍歷和提取。
使用
Array.from(new Set(data.map(item => item.method))) 獲取方法數(shù)組征炼,使用 Set 去重并轉(zhuǎn)換為數(shù)組析既。
使用
methodArray.map() 創(chuàng)建 seriesData 數(shù)組,直接遍歷方法數(shù)組并構(gòu)建每個方法的數(shù)據(jù)對象谆奥。
在
data 屬性中使用 xAxisData.map(date => totalsByMethod[date][method] || 0)眼坏,一次性獲取每個方法在各個日期的總數(shù)值。
這些優(yōu)化步驟有助于減少代碼中的重復(fù)計算和遍歷次數(shù)雄右,并提高了代碼的可讀性和簡潔性空骚。