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"}}}
use this one
or
Your problem is that your phones object doesn't have a length property (unless you define it somewhere in the JSON that you return) as objects aren't the same as arrays, even when used as associative arrays. If the phones object was an array it would have a length. You have two options (maybe more).
Change your JSON structure (assuming this is possible) so that 'phones' becomes
(note there is no word-numbered identifier for each phone as they are returned in a 0-indexed array). In this response
phones.length
will be valid.Iterate through the objects contained within your phones object and count them as you go, e.g.
If you're only targeting new browsers option 2 could look like this