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.
Objects are used to store the information in key-value pairs, where a value can be any other data type or function. Unlike arrays and strings, objects don't have predefined length property to get the length of an object. So when we call length property on an object it will return undefined.
The "Cannot read property 'length' of undefined" error occurs when accessing the length property on an undefined value. To solve the error, make sure to only access the length property on data types that support it - arrays or strings. Here is an example of how the error occurs.
The object does not have a length property by default. The length property is only available to arrays and strings.
Answer: Use the Object. keys() Method You can simply use the Object. keys() method along with the length property to get the length of a JavaScript object. The Object. keys() method returns an array of a given object's own enumerable property names, and the length property returns the number of elements in that array.
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]]); }
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With