Whiskey T. Foxtrot Whiskey T. Foxtrot - 16 days ago 9
Javascript Question

Dimple.js doesn't like my Array

I have data.json in this format:

{
"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" }
]
}
]
}


// etc., more user objects

In my application: a selection of a user is made, an ajax call gets this data, I loop thru it to get only the selected user's weigh-in data, and I'm successfully rendering this data to a table.

Now I'm trying to use the same result in a Dimple chart but Dimple evidently doesn't like my chartData array:

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();


... which results in a non-chart. However, if I console.log or alert(chartData) and set the result as chartData, i.e.:

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" }
]


... then I get a chart, ergo my confusion.

Any insight greatly appreciated,

Whiskey

Answer

You're pushing the JSON into your array as strings not objects, it should be:

chartData.push({ "User": selUser, "Date": dataDate, "Weight": dataWeight });

Which has the added benefit of being much easier to read!

Comments