Reputation: 21667
My goal is to be able to generate something exactly like this.
var data = google.visualization.arrayToDataTable([
['Year', 'Cost'],
['2004', 1000],
['2005', 1170],
['2006', 660],
['2007', 1030]
]);
But I am trying to get it done by using data that is generated by JSON
{
"uid": 1,
"name": "Cost",
"data": [
{
"year": 2009,
"cost": 640
},
{
"year": 2010,
"cost": 620
},
{
"year": 2011,
"cost": 600
},
{
"year": 2012,
"cost": 620
}
]
}
And by using this jQuery
$.getJSON("js/cost.json", function(d) {
console.log(d.data);
var items = [];
$.each( d.data, function( k, v ) {
console.log(v.cost);
console.log(v.year);
items.push("['"+v.year+"',"+v.cost+"]");
});
console.log(items);
});
But what I'm noticing is that its being pushed as a string, what is the correct way to push objects to an array so I can get this working.
Upvotes: 0
Views: 190
Reputation: 160973
.map
would be better than .each
.
$.getJSON("js/cost.json", function(d) {
var items = $.map(d.data, function(v) {
return [[v.year, v.cost]];
});
});
Upvotes: 4
Reputation: 76408
The data is being pushed as a string, because you are passing a string to items.push
. If you want an array, simply push an array:
items.push([v.year, v.cost]);
That's all you need to do.
By the looks of things, though, you want the year to be a string, and not a number, seeing as you're quoting the value of v.year
:
items.push("['" + v.year + "', " + v.cost + "]");
To do that, simply use JS's type coercion:
items.push([''+v.year, +(v.cost)]);
//concatenate with empty string => coerce to string
// +(someValue) coerces someValue to number
Upvotes: 3
Reputation: 133453
Currently your are creating a string and then pushing to array.
Use
items.push([v.year, v.cost]);
instead of
items.push("['"+v.year+"',"+v.cost+"]");
Upvotes: 5