Possible Duplicate:
Length of Javascript Associative Array
I have a JSON that looks like this:
Object: www.website1.com : "dogs" www.website2.com : "cats" >__proto__ : Object
This prints when I do this:
console.log(obj);
I am trying to get the count of the items inside this JSON, obj.length returns "undefined" and obj[0].length returns
Uncaught TypeError: Cannot read property 'length' of undefined
I would expect a length to return "2" in this case. How can I find the count?
Thanks!
To count the number key/value pairs in a JSON object we need to convert an array. And then we can easily count the number of element in the array which is same as the number key value pairs in the json object. Object.
JSON with duplicate key entries have to be handled either by ignoring the duplicate entries or by throwing an exception. Until Mule Runtimes 3.8. 6/3.9. 0, JSON Schema Validator handles them by retaining the last duplicate entry and not throwing an exception.
The names within an object SHOULD be unique. If a key is duplicated, a parser SHOULD reject. If it does not reject, it MUST take only the last of the duplicated key pairs.
You have to count them yourself:
function count(obj) { var count=0; for(var prop in obj) { if (obj.hasOwnProperty(prop)) { ++count; } } return count; }
Although now that I saw the first comment on the question, there is a much nicer answer on that page. One-liner, probably just as fast if not faster:
function count(obj) { return Object.keys(obj).length; }
Be aware though, support for Object.keys()
doesn't seem cross-browser just yet.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With