12

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?

2
  • it would be helpful to see what patientsData is like. Commented Aug 25, 2011 at 16:02
  • 1
    If you actually want to get the dimensions of an array (instead of an object), then see here: stackoverflow.com/a/13832026/975097 Commented Dec 15, 2012 at 4:43

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

Comments

4

.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

Comments

0

It appears that you are not using nested array, but are using objects nested within objects because you're accessing members by their names (rather than indexes).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.