How do you get the number of keys in a JSON object?

I am creating a gallery plugin in which I need to find out the number of elements in a simple javascript object. Next, as I would like to be able to create a gallery.

$.Gallery.create($('#galContainer'), { 'img1.png': 'http://linktosomewhere/', 'img2.png': 'http://linktosomewhere/', 'img3.png': 'http://linktosomewhere/', ........ }, optionsObj); 

This will put the images in the gallery with the corresponding links to any page when clicked. I am currently using an array for this second parameter with no links, and I am getting the length of the images using images.length. However, using the notation above would be ideal for me, and I would need to find out how many keys are in this object.

I know this post and several others saying that you cannot get the number of elements in an object. If this is true, do you have any suggestions on another way to configure this function call to be efficient and easy to use?

+4
source share
4 answers

Can't you use an array of objects?

 $.Gallery.create($('#galContainer'), [ {src:'img1.png', href:'http://linktosomewhere/'}, {src:'img2.png', href:'http://linktosomewhere/'}, {src:'img3.png', href:'http://linktosomewhere/'}, ........ ], optionsObj); 

You just need to add .src and .href to your code to read it.

The way to create your data set as a simple hash is not very flexible for additional attributes (size, categories, selected, etc.)

+2
source

The code you see in the other question you contacted is really the only way to do this. Here you can create a function for this:

 function count(obj) { var i = 0; for (var x in obj) if (obj.hasOwnProperty(x)) i++; return i; } 
+7
source

Underscore.js has a method that tells you how big the _.size(obj); object is _.size(obj);

+1
source
 Object.prototype.count = function() { var c = 0;var i; for(i in this){if (this.hasOwnProperty(i)){c++;}}; return c; } 

Personally, I would create my own prototype for Object, you can use MyObject.length , but I think it is not fully supported by IE.

Test

indicates that the length variable is not available in Object.

TestCase:

 MyObject = { a : '0', b : '1', c : '2' } if(MyObject.count() > 5) { $.Gellery.Error('Images','Only 5 images allowed'); //... } 

http://jsfiddle.net/b9Nwv/

0
source

All Articles