gpt4 book ai didi

javascript - Highcharts 循环 JSON 对象来填充数据系列

转载 作者:行者123 更新时间:2023-12-03 00:32:48 25 4
gpt4 key购买 nike

我对 Java 脚本非常陌生,我正在尝试弄清楚如何循环我的 JSON 对象并使用以下 JSON 对象填充 Highcharts 数据系列。我已经模拟了我试图用 JS Fiddle 做什么的静态显示。 JsFiddleLink

有人可以帮我解决这个问题吗?

这是我的 JSON 对象,我想循环遍历并填充 Highcharts 数据系列。

{
"OuterKey": {
"v4_acl": {
"aggregate": 100,
"S1": 40,
"S2": 30,
"S3": 20,
"S4": 10
},
"v6_acl": {
"aggregate": 120,
"S1": 14,
"S2": 13,
"S3": 12,
"S4": 11
},
"v4_qos": {
"aggregate": 125,
"S1": 30,
"S2": 14,
"S3": 17,
"S4": 19
},
"v6_qos": {
"aggregate": 80,
"S1": 22,
"S2": 21,
"S3": 20,
"S4": 23
},
"v4_nf": {
"aggregate": 90,
"S1": 20,
"S2": 20,
"S3": 20,
"S4": 26
},
"v6_nf": {
"aggregate": 111,
"S1": 11,
"S2": 44.5,
"S3": 45,
"S4": 80.5
},
"baseline": {
"aggregate": 130,
"S1": 60,
"S2": 10,
"S3": 10,
"S4": 10
}
}
}

这里还有静态显示的渲染图表的屏幕截图。

enter image description here

最佳答案

我认为这可以实现您需要的转换:

const raw = {
"OuterKey": {
"v4_acl": {
"aggregate": 100,
"S1": 40,
"S2": 30,
"S3": 20,
"S4": 10
},
"v6_acl": {
"aggregate": 120,
"S1": 14,
"S2": 13,
"S3": 12,
"S4": 11
},
"v4_qos": {
"aggregate": 125,
"S1": 30,
"S2": 14,
"S3": 17,
"S4": 19
},
"v6_qos": {
"aggregate": 80,
"S1": 22,
"S2": 21,
"S3": 20,
"S4": 23
},
"v4_nf": {
"aggregate": 90,
"S1": 20,
"S2": 20,
"S3": 20,
"S4": 26
},
"v6_nf": {
"aggregate": 111,
"S1": 11,
"S2": 44.5,
"S3": 45,
"S4": 80.5
},
"baseline": {
"aggregate": 130,
"S1": 60,
"S2": 10,
"S3": 10,
"S4": 10
}
}
};

const seriesObj = Object.values(raw.OuterKey)
.reduce((memo, v) => {
for (s in v) {
memo[s] = memo[s] || [];
memo[s].push(v[s]);
}
return memo;
}, {});

const series = Object.entries(seriesObj)
.map(([name, data]) => ({name, data}));

Highcharts.chart('container', {
title: {
text: 'My JSON Chart'
},
yAxis: {
title: {
text: 'JSON VALUE'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
xAxis: {
categories: Object.keys(raw.OuterKey),
crosshair: true
},
series
});
#container {
min-width: 310px;
max-width: 800px;
height: 400px;
margin: 0 auto
}
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/series-label.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/export-data.js"></script>

<div id="container"></div>

关于javascript - Highcharts 循环 JSON 对象来填充数据系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53785385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com