0

I've got the following code:

$(document).ready(function() {
    var blu = getData();
    console.log(blu); //this shows full the array in the console
    console.log(blu.length); //this gives back 0

});

With the following function getData()

function getData() {
    var arr = [];
    var json;

    $.ajax({
        url: "someurl.com",
        dataType: 'json',
        data: json,
        success: function(json) {
            var x = json.somejson.somenumericvalue //gets the amount of dataentries
            for (i = 0; i <= x - 1; i++) {
                arr.push(json.feeds[i].field1); // fill up array with the values from the json feed
            }
        } //end of success function
    }); //end of ajax
    console.log(arr.length) //shows the correct length of the array
    return arr;
} //end of function getData

Problem is I want to access the values and do methods (like .length) with the array which is filled in the function but it somehow does not work. Anyone can help out? Cheers.

Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40

3 Answers3

0

You can use $.each or for in loop

E.g.

$.each(Blu, function (i, v){//do whatever with array values, i: index, v: value}

Or

For(i in Blu){//i: index, access your value by Blu[I] & do whatever with your value}

Hope it'll help you out

Pradeep Rajput
  • 724
  • 7
  • 11
0

It is not clear what your json looks like, you probably need to iterate through it. Assuming that you want to iterate through json.feeds:

function getData(){
    var arr = [];
    var json;
    $.ajax({
        url: "someurl.com",
        dataType: 'json',
        data: json,
        success: function(json){
            for(var i in json.feeds) {
                arr.push(json.feeds[i].field1); // fill up array with the values from the json feed
            }
            console.log(arr.length)//shows the correct length of the array
            return arr;
        }    //end of success function
    });  //end of ajax
}//end of function getData

Also note where console.log and return is. I would suggest reading a basic book about javascript, specifically closures and variable scope. That's why your code doesn't work and the problem is not in ajax, json, or object iterating.

Michael Zelensky
  • 2,012
  • 3
  • 29
  • 37
0

The json data returned by the ajax call must be accessed by object notation if it is a named array. To retrieve the length of such an data object use:

Object.keys(data.datanode).length
Chris P. Bacon
  • 533
  • 2
  • 15