(javascript) function returning undefined [duplicate]

1

I'm trying to return a value from one function to another, get_Positions () has to get the lat and lng from parseJson (date), it's just returning undefined.  I want to get these two values from within get_Positions ().

get_Positions();
      function get_Positions(){
        $.ajax({
          url: 'http://taxer-cc.umbler.net/read.php',
          type: 'POST',
          dataType: 'html',
          data: 'value1=1'
        })
        .done(function(data) {
          var lct = parseJson(data);
          console.log(lct);
        })
        .fail(function(e) {
          console.log("Error: "+e);
        });
        function parseJson(data){
          $.each($.parseJSON(data), function (item, value) {
            $.each(value, function (i, k) {
              var location = function(){
                lat = k.lat;
                lng = k.lng;
                return [lat,lng];
              }
              loc = location();
              lat = loc[0];
              lng = loc[1];
              return [lat,lng];
            });
          });
        }
      }
    
asked by anonymous 06.01.2018 / 07:36

1 answer

2

The parseJson function returns nothing. The return [lat,lng]; you added is returning the value for the $.each callback and not for the parseJson function.

The correct one is:

function parseJson(data) {
    var result = [];

    $.each($.parseJSON(data), function(item, value) {
        $.each(value, function(i, k) {
            var location = function() {
                lat = k.lat;
                lng = k.lng;
                return [lat, lng];
            }
            loc = location();
            lat = loc[0];
            lng = loc[1];

            console.log([lat, lng]);

            result = [lat, lng];
        });
    });

    return result;
}

You can also use it this way:

function parseJson(data){
     /* Transforma a string json em objeto */
     let result = JSON.parse(data);

     /* Captura a primeira key do objeto */
     let key = Object.keys(result)[0];

     /* Retorna os valores. */
     return [result[key][0].lat, result[key][0].lng];
}
    
06.01.2018 / 07:44