Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 343
Metropolis Avatar asked Dec 29 '22 07:12

Metropolis


2 Answers

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;
}
like image 139
casablanca Avatar answered Dec 30 '22 23:12

casablanca


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

like image 45
Mic Avatar answered Dec 31 '22 01:12

Mic