gpt4 book ai didi

Highcharts JSON 调用的 javascript 关联数组、循环和/或范围问题

转载 作者:行者123 更新时间:2023-11-28 19:43:18 24 4
gpt4 key购买 nike

我有一个 javascript 关联数组问题、循环问题和/或范围问题。我正在尝试从 postgresql 数据库调用数据,解析它,并在 Highchart 中实现它。

数据由五个系列组成,每个系列有五个项目(列/字段):

 [Object, Object, Object, Object, Object]

打开后,第五个对象如下所示:

4: Object
acronym: "1"
current: "3.4"
id: 1
name: "a"
pc1: "2.5"
previous: "2.4"
url: "http://myhost:3000/series/1.json"
__proto__: Object
length: 5
__proto__: Array[0]

解析后,我得到了一系列对象:

[Object]
[Object]
[Object]
[Object]
[Object]

其中包含期望的解析数据,即 k:v 对 [name: "a", y: 2.5]:

[Object]
0: Object
name: "a"
y: 2.5
__proto__: Object
length: 1
__proto__: Array[0]

但是,我需要的是一个对象数组:

[{name: "a", y: 2.5}, {name: "b", y: 3.0}, {name: "c", y: 1.0}, {name: "d", y: 2.0}, {name: "e", y: 3.2}]

如果我在下面插入“虚拟”数据,图表将正确呈现,因此问题出在我的代码上,特别是数组的创建及其在 JSON 函数之外的可用性。

[{name: 'name1', y: 2.5}, {name: 'name2', y: 4.0}];

任何和所有帮助将不胜感激。这是 Highchart 的完整 javascript 代码 - 附有问题所在的注释。

$(document).ready(function () {

var options = {
chart: {
renderTo: 'container',
type: 'column',
},

title: {
text: 'The Conference Board'
},

legend: {
enabled: false
},

subtitle: {
text: 'Leading Indicators '
},

xAxis: {
type: 'category',
labels: {
rotation: -45,
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},

credits: {
enabled: false
},

yAxis: {
title: {
text: 'Percent Change Year / Year'
},
},

series: [{
data: [] // dummy code inserted here makes the chart render

}]
};

url = "http://myhost:3000/series";
$.getJSON(url, function (series) {
console.log(series); // five series of five k:v pairs each

$.each(series, function(key_i, val_i) { // parsing to a single k:v (name: value) pair

data = []; // I'm trying to create an array of objects // [{},{},{},{},{}]
data.push({ // for insertion into the var options.series.data above
name: val_i.name,
y: parseFloat(val_i.pc1)
});

options.series[0].data = data;
console.log(options.series[0].data); // getting all k:val_i pairs sequentially; however, not as an array of objects

});
options.series[0].data = data;
console.log(options.series[0].data); // only getting the last k:v pair and the chart doesn't render
});

console.log(options.series[0].data); // an empty array []
var chart = new Highcharts.Chart(options);

});

再次提前感谢您对此提供的帮助。我已经为此工作了好几天了。

最佳答案

尝试

$.getJSON(url, function (series) {
options.series[0].data = $.map(series, function(val) {
return { name: val.name, y: parseFloat(val.pc1) };
});

new Highcharts.Chart(options);
});

更新修复现有每个循环

$.getJSON(url, function (series) {
var data = [];

$.each(series, function(val) {
data.push({ name: val.name, y: parseFloat(val.pc1) });
});

options.series[0].data = data;
new Highcharts.Chart(options);
});

关于Highcharts JSON 调用的 javascript 关联数组、循环和/或范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24689140/

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