Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check Length of Multidimensional Arrays with Javascript [duplicate]

Possible Duplicate:
Length of Javascript Associative Array

I want to check the length of a multidimensional array but I get "undefined" as the return. I'm assuming that I am doing something wrong with my code but I can't see anything odd about it.

alert(patientsData.length); //undefined
alert(patientsData["XXXXX"].length); //undefined
alert(patientsData["XXXXX"]['firstName']); //a name

fruits = ["Banana", "Orange", "Apple", "Mango"];
alert(fruits.length); //4

Thoughts? Could this have something to do with scope? The array is declared and set outside of the function. Could this have something to do with JSON? I created the array from an eval() statement. Why does the dummy array work just fine?

like image 601
BFTrick Avatar asked Aug 25 '11 16:08

BFTrick


2 Answers

Those are not arrays. They're objects, or at least they're being treated like objects. Even if they are Array instances, in other words, the "length" only tracks the largest numeric-indexed property.

JavaScript doesn't really have an "associative array" type.

You can count the number of properties in an object instance with something like this:

function numProps(obj) {
  var c = 0;
  for (var key in obj) {
    if (obj.hasOwnProperty(key)) ++c;
  }
  return c;
}

Things get somewhat messy when you've got inheritance chains etc, and you have to work out what you want the semantics of that to be based on your own architecture.

like image 157
Pointy Avatar answered Nov 17 '22 04:11

Pointy


.length only works on arrays. It does not work on associative arrays / objects.

patientsData["XXXXX"] is not an array. It's a object. Here's a simple example of your problem:

var data = {firstName: 'a name'};
alert(data.length); //undefined
like image 31
Eric Avatar answered Nov 17 '22 04:11

Eric