2

I'm trying to count the number of results in my $.ajax call.

    $.ajax({
        'async': true,
        'crossDomain': true,
        'url': 'XXX',
        'method': 'GET',
        'headers': {
            'key': 'XXX',
            'scope': 'XXX',
            'content-type': 'application/json',
            'cache-control': 'no-cache'
        },
        'processData': false,
        'data': {},
        error: function(jqXHR, textStatus, errorThrown) {
            // Default error
            log('error');

        },
        success: function(data, textStatus, jqXHR) {
            log('success');
            log(data);
            var ArrayContent = data.length;
            log(ArrayContent)

        }
    }).done(function(response) {
        log('done');
    });

My jSon response is Object {3858: Object, 4667: Object, 4668: Object, 4680: Object, 4710: Object}3858: Object4667: Object4668: Object4680: Object4710: Object__proto__: Object

I have tried several solutions found on this site, but I cant get any of them to work.

Any suggestion towards a solution would be very much appreciated.

-C

iamchriswick
  • 380
  • 2
  • 8
  • 24

3 Answers3

9

You can find the number of own enumerable properties in the object using this code:

Object.keys(response).length;
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
Aju John
  • 2,214
  • 1
  • 10
  • 27
  • Ya but then a comment would be better/more useful than a downvote ;) – A. Wolff Apr 15 '16 at 13:46
  • 1
    Comments needs to be typed...but downvote is easy..just a click...:-P – Aju John Apr 15 '16 at 13:47
  • That was me, then I got distracted mid comment... I dislike the content of your answer. The code may be fine, but (as far as I'm concerned) any variation of "Try this" doesn't make for a good answer. "Try this" is a suggestion or request, neither of which gives any confidence to the reader that you're actually sure about the information you're providing. Stick to statements such as "You can find the number of keys in the object using this code:" instead. – Anthony Grist Apr 15 '16 at 13:53
1

Check out the length of the json returned to your ajax function

var count = Object.keys(data).length;

Velimir Tchatchevsky
  • 2,812
  • 1
  • 16
  • 21
-1
var json = JSON.parse(result);
var lengthofObject = json.length; // this is the number of elements in your response
Saad Mujeeb
  • 106
  • 1
  • 3