我有这种格式的data.json:
{
"Users": [
{
"userName": "Herbie",
"weigh-in data": [
{ "date": "2016.01.04", "weight": "114.3" },
{ "date": "2016.01.05", "weight": "114.6" },
{ "date": "2016.01.06", "weight": "114.9" }
]
},
{
"userName": "Wayne",
"weigh-in data": [
{ "date": "2016.02.01", "weight": "120.3" },
{ "date": "2016.02.05", "weight": "123.6" },
{ "date": "2016.02.06", "weight": "123.9" }
]
}
]
}
//等等,更多的用户对象
在我的应用程序中:选择了一个用户,一个ajax调用获取了该数据,我循环遍历该数据以仅获取所选用户的称量数据,然后成功地将此数据呈现到表中。
现在,我试图在Dimple图表中使用相同的结果,但是Dimple显然不喜欢我的chartData数组:
var dataObj = JSON.parse(jsonData);
var usersArray = dataObj.Users;
var chartData = [];
// etc. SNIP
for (var obj of usersArray) {
if (obj.userName === selUser) { // weigh-ins of the selected user only
dataRows.innerHTML = "";
for (var i = 0, j = selUserData.length; i < j; i++) {
var dataDate = selUserData[i].date;
var dataWeight = selUserData[i].weight;
chartData.push('{ "User"' + ': ' + '"'+selUser+'", ' + '"Date":' + ' ' + '"'+dataDate+'", ' + '"Weight":' + ' ' + '"'+dataWeight+'" }');
// SNIP: build rows from the data, load up the table, no problem
dataRows.innerHTML += row;
} // selUserData loop
var svg = dimple.newSvg("#chartContainer", 800, 600);
var chart = new dimple.chart(svg, chartData);
chart.setBounds(60, 30, 505, 305);
var x = chart.addCategoryAxis("x", "Date");
x.addOrderRule("Dates");
var y = chart.addCategoryAxis("y", "Weight");
y.addOrderRule("Weights");
var s = chart.addSeries("weigh-ins", dimple.plot.line);
chart.draw();
...这会导致图表无效。但是,如果我用console.log或alert(chartData)并将结果设置为chartData,即:
var chartData = [
{ "User": "Wayne", "Date": "2016.02.01", "Weight": "180.3" },
{ "User": "Wayne", "Date": "2016.02.05", "Weight": "123.6" },
{ "User": "Wayne", "Date": "2016.02.06", "Weight": "153.9" }
]
...然后我得到了一张图表,因此感到困惑。
任何见解都非常感谢
威士忌酒
最佳答案
您将JSON作为字符串而不是对象推入数组,它应该是:
chartData.push({ "User": selUser, "Date": dataDate, "Weight": dataWeight });
这样做的另一个好处是易于阅读!
关于javascript - Dimple.js不喜欢我的数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40665767/