jQuery JSON to multi dimensional array

时间:2015-04-29 00:23:39

标签: javascript jquery arrays json

So I have a jQuery .getJson which is as so:

var tournamentdata = [];

$.getJSON( "http://tourn.dev/data/tournaments", function( data ) {

  $.each(data, function(i) {

     var tempdata = [];

     $.each(this, function(k, v) {
        tempdata.push(v);
     });

     tournamentdata.push(tempdata);

  });

});

console.log(tournamentdata);

The JSON request returns:

[
    {
        "id":1,
        "name":"one",
        "max_users":100,
        "registered_users":0,
        "prize_pool":1000,
        "entry_fee":10,
        "published":0,
        "registration_open_date":"0000-00-00 00:00:00",
        "registration_close_date":"0000-00-00 00:00:00"
        ,"start_date":"0000-00-00 00:00:00",
        "created_at":"2015-04-28 20:35:23",
        "updated_at":"2015-04-28 20:35:23"
    },
    {
        "id":2,
        "name":"Two",
        "max_users":1000,
        "registered_users":0,
        "prize_pool":10000,
        "entry_fee":100,"published":0,
        "registration_open_date":"0000-00-00 00:00:00",
        "registration_close_date":"0000-00-00 00:00:00",
        "start_date":"0000-00-00 00:00:00",
        "created_at":"2015-04-28 20:37:16",
        "updated_at":"2015-04-28 20:37:16"
    }
]

Now, when I check my console log in firefox the tournamentdata is an array of two arrays 'Array [ Array[12], Array[12] ]'.

However, when I try access the multi-array through something like:

alert(tournamentdata[0][0]); 

it returns undefined.

1 个答案:

答案 0 :(得分:1)

你在控制台看到的是数组的实时reference,它看起来正确....但它不是快照,它会随着数组的变化而改变

然而,尝试在相关代码中对其进行字符串化,您将看到的只是空数组。为什么?因为在您尝试访问数据时ajax尚未完成。

实时引用看起来正确,因为控制台没有显示exaclty记录时的数组外观,它还会显示所有后续更改......由于原型继承

您可以在此演示代码中看到它:

var tournamentdata = [];

$.getJSON("data.json", function(data) {

  $.each(data, function(i) {
    var tempdata = [];
    $.each(this, function(k, v) {
      tempdata.push(v);
    });
    console.log('Push data now'); //fires after the one below
    tournamentdata.push(tempdata);

  });

});
//this log is empty array and fires before the above logs
console.log('Log outside getJSON', JSON.stringify(tournamentdata));

结论:如果要访问数组并解析为DOM,则必须在$.getJSON回调中完成... A中的第一个ajax代表{{1} }}

要获得非常好的解释,必须阅读使用ajax的任何人,请参阅:How to return the response from an asynchronous call?

DEMO