简体   繁体   中英

How to convert Getjson to values in a dictionary or array in Javascript

I have a Javascript function and get the below values in console if I run the codes:

$(document).ready(function(){
    $.getJSON('http://example.com/json.php',function(urldata){
         console.log(urldata);
    });
})

I get the below in console:

{data: Array(3), draw: 1, recordsTotal: 3, recordsFiltered: 30}
data: Array(3)
0: (6) [1, 'Tokyo', 'Japan', '83', '9', 0]
1: (6) [2, 'Paris', 'France', '16', '8', 0]
2: (6) [3, 'Rome', 'Italy', '44', '6', 0]
length: 3
[[Prototype]]: Array(0)

I tried to put them in an array but I got undefined error message.

var arr = [];
    $(document).ready(function(){
        $.getJSON('http://example.com/json.php',function(urldata){
             for(k in urldata)
            {
               alert("City: " + k[1] + " Country: " + k[2]);
               arr.push(k[1], k[2])
            }
        });
    })

I would like to have the below output in an array or dictionary with easy access to the values:

+---+-------+--------+
| 1 | Tokyo | Japan  |
+---+-------+--------+
| 2 | Paris | France |
+---+-------+--------+
| 3 | Rome  | Italy  |
+---+-------+--------+

Please, what is wrong with the code?

Based on the structure of the response, try replacing your callback to arr.push(urldata.data)

let arr = [];
    $(document).ready(function(){
        $.getJSON('http://example.com/json.php',function(urldata){
            arr.push(urldata.data)
            // console.log(urldata)
        });
    })

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