How can I count # of responses in jQuery $.ajax result?

17,064

Solution 1

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

Object.keys(response).length;

Solution 2

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

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

Share:
17,064

Related videos on Youtube

iamchriswick
Author by

iamchriswick

SOreadytohelp

Updated on June 06, 2022

Comments

  • iamchriswick
    iamchriswick almost 2 years

    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

  • Velimir Tchatchevsky
    Velimir Tchatchevsky about 8 years
  • A. Wolff
    A. Wolff about 8 years
    Ya but then a comment would be better/more useful than a downvote ;)
  • Aju John
    Aju John about 8 years
    Comments needs to be typed...but downvote is easy..just a click...:-P
  • Anthony Grist
    Anthony Grist about 8 years
    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.
  • Uyghur Lives Matter
    Uyghur Lives Matter about 8 years
    The response is an Object, not an Array.