javascriptjson

get size of JSON object


i have a JSON object that gets returned by an AJAX request and I am having some trouble with the .length because it keeps returning undefined. Just wondering if I'm using it right:

console.log(data.length);
console.log(data.phones.length);

They both return undefined even though they are valid objects.

Update:
Sample of the JSON object returned:

{"reqStatus":true,"phones":{"one":{"number":"XXXXXXXXXX","type":"mobile"},"two":{"number":"XXXXXXXXXX","type":"mobile"}}}

Solution

  • You can use something like this

    var myObject = {'name':'Kasun', 'address':'columbo','age': '29'}
    
    var count = Object.keys(myObject).length;
    console.log(count);