Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript associative array length using jQuery

I am using javascript associative array like:

var testarray = [];
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';

I am also using jquery alongside. How can I check length of this associative array using jquery or any other method? Basically i want to check whether this array is empty or not.

Thank you.

like image 939
Prashant Avatar asked Mar 08 '10 15:03

Prashant


3 Answers

You shouldn't use an array to store non-numeric indexes, you should use a simple object:

function getObjectLength (o) {
  var length = 0;

  for (var i in o) {
    if (Object.prototype.hasOwnProperty.call(o, i)){
      length++;
    }
  }
  return length;
}

Edit: Since you are using jQuery and you want to check if the object is "empty", the 1.4 version introduced the $.isEmptyObject

if ($.isEmptyObject(obj)) { 
  //...
}
like image 135
Christian C. Salvadó Avatar answered Nov 07 '22 02:11

Christian C. Salvadó


This gives you the length of your associative array:

Object.keys(testarray).length
like image 22
Aditya Avatar answered Nov 07 '22 02:11

Aditya


There's no direct "length" or "size" call, you have to test the keys available within the object.

Note that all JavaScript objects are associative arrays (maps), so your code would probably be better off using a generic object rather than an array:

var testarray = {}; // <= only change is here
testarray['one'] = '1';
testarray['two'] = '2';
testarray['three'] = '3';

You can find out what the keys are in an object using for..in:

var name;
for (name in testarray) {
    // name will be 'one', then 'two', then 'three' (in no guaranteed order)
}

...with which you can build a function to test whether the object is empty.

function isEmpty(obj) {
    var name;
    for (name in obj) {
        return false;
    }
    return true;
}

As CMS flagged up in his answer, that will walk through all of the keys, including keys on the object's prototype. If you only want keys on the object and not its prototype, use the built-in hasOwnProperty function:

function isEmpty(obj) {
    var name;
    for (name in obj) {
        if (obj.hasOwnProperty(name)) {
            return false;
        }
    }
    return true;
}
like image 10
T.J. Crowder Avatar answered Nov 07 '22 04:11

T.J. Crowder