4

I am creating a gallery plug-in in which I need to figure out the number of elements in a plain javascript object. The following is how I would like to be able to create the gallery.

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

This will put the images into the gallery with the corresponding links to some page when clicked. Currently I am using an array for that second parameter without the 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 need to be able to tell how many keys there are in this object.

I am aware of this post and a few others saying you can not get the number of elements in the object. If this is indeed the case, do you have any suggestions on another way to setup this function call which will be efficient and easy to use?

Community
  • 1
  • 1
Metropolis
  • 6,322
  • 17
  • 54
  • 81

4 Answers4

7

The code you see in the other question you linked to is really the only way to do it. Here's how you can create a function to do it:

function count(obj) {
  var i = 0;
  for (var x in obj)
    if (obj.hasOwnProperty(x))
      i++;
  return i;
}
casablanca
  • 66,266
  • 7
  • 126
  • 145
  • 1
    You should also declare `x` with `var`. Current version use global `x`. – Oleg Sep 05 '10 at 16:15
  • Thanks casa, I will definitely add this to my arsenal of functions, and use it later. But I think for this particular instance I would rather not rely on this. – Metropolis Sep 05 '10 at 20:27
2

Can't you use an array of objects instead?

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

You should just add a .src and .href in your code to read it.

The way you designed your dataset as a simple hash is not very flexible for additional attributes(size, categories, selected, etc...)

Mic
  • 23,536
  • 8
  • 55
  • 69
1

Underscore.js has a method that will tell you how large the object is _.size(obj);

chovy
  • 59,357
  • 43
  • 187
  • 234
0
Object.prototype.count = function()
{
   var c = 0;var i;
   for(i in this){if (this.hasOwnProperty(i)){c++;}};
   return c;
}

Personally I would build your own prototype for Object, you can use MyObject.length but I think its not fully supported by IE.

test reveal that the length variable is unavailable in Objects.

Testcase:

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

http://jsfiddle.net/b9Nwv/

RobertPitt
  • 54,473
  • 20
  • 110
  • 156
  • 1
    You should also declare `i`,`c` with `var`. Current version use global `i` and `c`. – Oleg Sep 05 '10 at 16:16