0

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.

1
  • 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. Commented Jun 11, 2014 at 8:58

3 Answers 3

5

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+"]");
Sign up to request clarification or add additional context in comments.

Comments

4

.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.

2 Comments

@KingKing You are right, I fixed the code. But it could return [['Year', 'Cost'], ...].
I've just found out that way myself, look at here you've already fixed it :)
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.