Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
    
I wonder what made you push a string in the first place. I mean, it looks like you know what arrays are, since you are using them. –  Felix Kling Jun 11 at 8:58
add comment

3 Answers

up vote 4 down vote accepted

.map would be better than .each.

$.getJSON("js/cost.json", function(d) {
  var items = $.map(d.data, function(v) {
    return [[v.year, v.cost]];
  });
});

The demo.

share|improve this answer
    
@KingKing You are right, I fixed the code. But it could return [['Year', 'Cost'], ...]. –  xdazz Jun 11 at 9:29
    
I've just found out that way myself, look at here you've already fixed it :) –  King King Jun 11 at 9:35
add comment

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
share|improve this answer
add comment

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+"]");
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.