简体   繁体   中英

jQuery .each() creating object array

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.

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+"]");

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM