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.

3
  • 2
    An object doesn't have any length, arrays does Commented Jun 16, 2015 at 7:47
  • What length did you expect? 2? 8? 16? Commented Jun 16, 2015 at 7:50
  • I found this question while investigating why in my case an actual array assigned to [] and then having one item pushed to it, has a length of undefined. Commented Nov 9, 2023 at 12:24

3 Answers 3

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]]);
}
Sign up to request clarification or add additional context in comments.

Comments

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 };

1 Comment

I didn't know (function(){}).length is number of arguments. Thanks for your sharing.
8

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

 alert(Object.keys(coordinates).length);

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.