How to return the length of a ajax/json object [Solved]


#1

Hi all,

I’ve been trying to return the count of my json result, without success. The problem is, the number always returns, but it’s wrong.

Wondering how I can return a basic counter of all the results return from the AJAX result.

Example
The API returns 100 posts, but the code below returns 42 :thinking:

var counter = x.length;
console.log(counter + ' items'); //42 items

Code - slightly reduced for viewing:

(function(){
  var x = 'https://jsonplaceholder.typicode.com/posts'; //100 posts
  var photoCall = $.ajax({
    dataType: 'jsonp',
    url: x
  });
  photoCall.done(function(data) {
    var template = $('#results_tpl').html();
    var html = Mustache.render(template, data);
    $results.html(html);

    var counter = x.length;
    console.log(counter + ' items');
  });
})();

Do I need a different approach, any ideas how I can get this to work?

Thanks, Barry


#2

Hi computerbarry,

x.length would be referring to the length (in characters) of the URL string ‘https://jsonplaceholder.typicode.com/posts’.

Maybe it is ‘data’ that you want to count. What format is data in, is it an array? You can console.log it to see what it is. If it’s an array of results then data.length should do.

Hope it helps


#3

Hey @Andres_Vaquero

I thought I’d tried this, been trying everything :upside_down_face:

I think I needed the second pair of eyes ha
This is working now, thanks :grin:

And yes this is an array, example:

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse"
  },
  ...
]

Updated

var counter = data.length;
console.log(counter + ' items'); //100 items

Barry


#4

I knew something wasn’t right @Andres_Vaquero :expressionless:

I’ve tested above with a sample api that uses an array without any parent keys. I have been using another json response which has an array but with a couple of parents which returns:

undefined items

The array is structured like:

{
"results": [
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse"
  },
  ...
]
}

How would I count the data like this, becasue undefined is now returned as mentioned above?

Thanks, and sorry for the misunderstanding.

Barry


#5

how about the following?
var counter = data.results.length;


#6

Cheers :grinning:
I should now this, nice reminder.

Working great!

Thanks again,
Barry