Skip to content Skip to sidebar Skip to footer

Object.length Undefined In Javascript

I have an javascript object of arrays like, var coordinates = { 'a': [ [1, 2], [8, 9], [3, 5], [6, 1] ], 'b': [ [5,

Solution 1:

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

Solution 2:

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

Solution 3:

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

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

Post a Comment for "Object.length Undefined In Javascript"