<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>test</title>
</head>
<body>
<div id="chart" style="width:600px;height:400px;"></div>
<script src="https://cdn.jsdelivr.net/npm/echarts@5.4.0/dist/echarts.js"></script>
<script type="text/javascript">
let data = [
{
"classNum": "夜班",
"userCountList": [
{
"userName": "hulubing",
"sum": 11
},
{
"userName": "admin123",
"sum": 4
},
{
"userName": "linn_test",
"sum": 1
},
{
"userName": "测试",
"sum": 1
}
]
},
{
"classNum": "晚班",
"userCountList": [
{
"userName": "hulubing",
"sum": 2
},
{
"userName": "admin123",
"sum": 2
}
]
},
{
"classNum": "白班",
"userCountList": [
{
"userName": "hulubing",
"sum": 1
},
{
"userName": "admin123",
"sum": 1
}
]
}
]
console.log(data)
for(let item of data){
let tmp = {}
// console.log(item)
console.log(item.userCountList)
for(let k of item.userCountList){
// console.log(k)
tmp[k.userName] = k.sum // 数组转换对象
item.list = tmp // 创建新节点存储对象
// console.log(tmp)
}
console.log(tmp)
}
let classNums = []
// 创建一个新数组存储新的数据结构
let newData = data.map(v => {
console.log(v)
classNums.push(v.classNum)
return {
name: v.classNum,
type: 'bar',
barWidth: "20%", // 柱状宽度
data: Object.values(v.list),
values: v.userCountList.map(v=>v.userName),
barCategoryGap:'120px',
label: {
show: true,
position: 'top'
},
}
})
// console.log(JSON.stringify(newData))
// 班次
// console.log(classNums)
// 姓名
let classValUsers = newData.map(v=>v.values)
// console.log(classValUsers)
function initCharts () {
let myChart = echarts.init(document.getElementById('chart'),'light');
// 绘制图表
myChart.setOption({
color: ['#00aaff', '#00FFA6', '#F4DF58'],
tooltip: {
confine: true,
},
legend: {
right: "25%",
top:"4%",
data: classNums,
itemGap: 20,
itemWidth: 20,
itemHeight: 10,
textStyle: {
color: "#000",
fontSize: 14,
},
},
grid: {
left: '10%',
right: '4%',
bottom: '3%',
containLabel: true
},
//工具
toolbox: {
//是否显示
show: true,
right: "4%",
top:"2%",
feature: {
//折线图 与 柱状图 切换
magicType: {
type: ['line', 'bar']
},
//下载
saveAsImage: {}
}
},
tooltip: {
trigger: "axis",
backgroundColor: "rgba(33,56,77,1)",
borderColor: "rgba(33,56,77,1)",
textStyle: {
color: "#fff",
fontSize: 14,
},
axisPointer: {
lineStyle: {
color: "rgba(0,133,255,0)",
},
},
},
xAxis: {
type: 'category',
data: classValUsers[0],
axisLabel: {
//坐标轴刻度标签的相关设置
margin: 15, //刻度标签与轴线之间的距离
},
},
yAxis: [
{
type: "value",
name:"单位(天)",
namestyle:{
color:"#000000",
},
boundaryGap: ['0', '20%'],
axisLabel: {
textStyle: {
color: "#000000",
fontSize: 14,
},
},
axisTick: { show: true },
axisLine: { show: true },
splitLine: { show: true },
}
],
series: newData
})
}
initCharts()
</script>
</body>
</html>
符合Echarts数据结构的数组对象转换第二版
最新推荐文章于 2023-07-07 14:45:54 发布