Counting the number of properties in an Object not completely simple. There is no property that will tell you directly, and if you for...in count them over them, you will also get inherited properties, so if someone defines something on Object.prototype , you will get the wrong answer.
In ECMAScript Fifth Edition, you get getOwnPropertyNames , which returns an array of non-inherited property names:
var options= {'1': 'a', '2': 'b'}; Object.getOwnPropertyNames(options).length;
For browsers that do not yet support Fifth Edition (primarily IE <= 8), you can pin it:
if (!('getOwnPropertyNames' in Object)) { Object.getOwnPropertyNames= function(o) { var names= []; for (var k in o) if (Object.hasOwnProperty(k)) names.push(k); return names; }; }
However, if you have control over the JSON output format, I would strongly suggest turning your Options object into a simple array, which would seem to be much better modeling of your data. With an array, you can just use Options.length .
source share