开发者

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

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开发者_StackOverflow社区 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?


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;
}


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...)


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


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜