0

I'm trying to figure out how many properties are in the following object. Obviously, I can see 2, but I need to know dynamically.

var test = $.parseJSON('{ "ddSize": "Size", "ddColor": "Color" }');

If I try:

var mylen = test.length;

.length is undefined. The number of properties in this object will change. Sometimes it's 1, sometimes 2 or 3, but I just can't figure out how to test it.

rwkiii
  • 5,368
  • 17
  • 60
  • 102
  • 1
    possible duplicate of [How to efficiently count the number of keys/properties of an object in JavaScript?](http://stackoverflow.com/questions/126100/how-to-efficiently-count-the-number-of-keys-properties-of-an-object-in-javascrip) – Colin Brock Jul 06 '12 at 21:26
  • `Object.keys(obj).length` looks like a graceful way of doing it, but it seems to have compatibility limitations. I'm targeting all major browsers including IE back to IE7. Thank you for the link, there are a lot of ways to do this apparently. – rwkiii Jul 06 '12 at 21:34
  • This previous question might also interest you: http://stackoverflow.com/questions/5223/length-of-javascript-object-ie-associative-array – Colin Brock Jul 06 '12 at 21:36
  • `Object.keys(obj).length` returns '1' and unless it's zero-based its not what I'm looking for. I think the answer (using my example object) is '2'. I'll look at your second reference. Thanks! – rwkiii Jul 06 '12 at 21:41

1 Answers1

3

This is a JavaScript JSON object. length function is not available.

First solution with pure JavaScript:

var data = $.parseJSON('{ "ddSize": "Size", "ddColor": "Color" }'); 
var keys = [];
for (key in data) {
  keys.push(key);
}
// numberOfKeys should equal to 2
var numberOfKeys = keys.length;

Second solution if you prefer jQuery:

var data = $.parseJSON('{ "ddSize": "Size", "ddColor": "Color" }');
var keys = [];
$.each(data, function(key, value) {
  keys.push(key)
});
// numberOfKeys should equal to 2
var numberOfKeys = keys.length;

Documentation for jQuery.each function

activars
  • 1,662
  • 13
  • 15
  • This way also returns '1' using my example data. I used the jQuery method. Just seems like it should be '2'. – rwkiii Jul 06 '12 at 21:49
  • Please double check your code or show me the exact code you are using? I also updated the example, try to copy and paste into FireBug or Webkit console. – activars Jul 06 '12 at 21:55
  • I do get the correct result now. I was enclosing my data string with '[' and ']' while trying a different method. Your second example works as expected. Thank you! – rwkiii Jul 06 '12 at 22:06
  • Also, take a look underscore.js if you are going to play with javascript collection a lot. http://underscorejs.org/ – activars Jul 06 '12 at 22:13