Search code examples
javascriptjqueryajaxjsonresponse

JSON response data length getting undefined error in Ajax?


I want to get the length of language in JavaScript alert box -

See screenshot-

Ajax Response -

enter image description here

enter image description here

My Ajax code -

function search_menu(){
    $.ajax({
        type: 'post',
        url: rootUrl() + "rest_apis/search_menu.json", 
        cache: false,        
        success: function(res){ //alert(data.data[0].language[142]);
            var len = res.data[0].language.length; 
            alert(len); //Showing undefined
        },
        contentType: 'application/json',
        dataType: 'json'
    });
}

I am just alerting alert(lang) its showing undefined. Actually in language having 36 record. why its showing undefined?


Solution

  • Try : Object.keys(res.data[0].language).length

    Live example :

    var res = {
            "data" : [
                    {
                      "language" : { "107":"english", "142":"hindi", "143" : "indonesian"}
                    }
            ]
    }
    
    
    alert("There are " + Object.keys(res.data[0].language).length + " languages." )