27

I have an javascript object of arrays like,

var coordinates = {
     "a": [
         [1, 2],
         [8, 9],
         [3, 5],
         [6, 1]
     ],

         "b": [
         [5, 8],
         [2, 4],
         [6, 8],
         [1, 9]
     ]
 };

but coordinates.length returns undefined. Fiddle is here.

mpsbhat
  • 2,733
  • 12
  • 49
  • 105

3 Answers3

31

That's because coordinates is Object not Array, use for..in

var coordinates = {
     "a": [
         [1, 2],
         [8, 9],
         [3, 5],
         [6, 1]
     ],

     "b": [
         [5, 8],
         [2, 4],
         [6, 8],
         [1, 9]
     ]
 };

for (var i in coordinates) {
  console.log(coordinates[i]) 
}

or Object.keys

var coordinates = {
  "a": [
    [1, 2],
    [8, 9],
    [3, 5],
    [6, 1]
  ],

  "b": [
    [5, 8],
    [2, 4],
    [6, 8],
    [1, 9]
  ]
};

var keys = Object.keys(coordinates);

for (var i = 0, len = keys.length; i < len; i++) {
  console.log(coordinates[keys[i]]);
}
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
10

coordinates is an object. Objects in javascript do not, by default, have a length property. Some objects have a length property:

"a string - length is the number of characters".length

['an array', 'length is the number of elements'].length

(function(a, b) { "a function - length is the number of parameters" }).length

You are probably trying to find the number of keys in your object, which can be done via Object.keys():

var keyCount = Object.keys(coordinates).length;

Be careful, as a length property can be added to any object:

var confusingObject = { length: 100 };
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Armand
  • 23,463
  • 20
  • 90
  • 119
8

http://jsfiddle.net/3wzb7jen/2/

 alert(Object.keys(coordinates).length);
AshBringer
  • 2,614
  • 2
  • 20
  • 42