Get first value of an array in javascript

0
<script src="http://code.jquery.com/jquery-2.1.0.min.js"> </script>

<script>
    var coordenadas;
    function testAjax() {
        $.ajax({
            url: 'https://dev.datos.ua.es/uapi/5QGUfP3UM6j5VXERjKvU/datasets/11/data', type: 'GET',
            dataType: "jsonp",
            success: function (data) {
                $.each(data, function (i, item) {                        
                   coordenadas = item.bbox.split(',');
                   console.log(coordenadas[1], coordenadas[0]);   

                });
            }
        });
    }

</script> 
<script>testAjax();</script>

Having that code, I get many latitudes and longitudes, a list of all of them but I would like to take only the first pair of longitude and latitude of all, since I only get them all out.

    
asked by Kora 15.10.2017 в 19:29
source

2 answers

0
  

Thanks, but from the jsonp data I need them all, once I have them, I want to use each pair individually to put them on a map

Ah, then what you want is not only the first result, but the first 2 results of each result (your question is made confusingly). In which case, you must only declare an Array, and within the $.each use the function push() .

Example:

<script src="http://code.jquery.com/jquery-2.1.0.min.js"> </script>

<script>
    var coordenadas;
    var buffer = new Array();
    function testAjax() {
        $.ajax({
            url: 'https://dev.datos.ua.es/uapi/5QGUfP3UM6j5VXERjKvU/datasets/11/data',
            type: 'GET',
            dataType: "jsonp",
            success: function (data) {
                $.each(data, function (i, item) {                        
                   coordenadas = item.bbox.split(',');
                   buffer.push([coordenadas[1], coordenadas[0]]);   
                });
            }
        });
    }

</script> 
<script>
    testAjax();
</script>

In this way you will be able to access the values of the 2D array more easily.

buffer[0][1]

It should be noted that since it is an asynchronous request, if you place ...

console.log(buffer[x][x])

After testAjax() , it will not work for time issues since it is all asynchronous, so that you will be able to access only from another declared function whose execution is given by an onclick, onkeypress or other event.

    
answered by 15.10.2017 / 20:38
source
0

The code is fine, you just have to modify this ...

success: function (data) {
    $.each(data, function (i, item) {                        
        coordenadas = item.bbox.split(',');
        console.log(coordenadas[1], coordenadas[0]);   
    });
}

Because of this ...

success: function (data) {                    
    coordenadas = data[0].bbox.split(',');
    console.log(coordenadas[1], coordenadas[0]);
}
    
answered by 15.10.2017 в 19:48