JavaScript: Get object size
How to get the size of an object in JavaScript#
Arrays in JavaScript have a length
property that gives you the number of items in an array. Objects on the other hand, don't have a length or size property.
var myArray = ['A', 'B'];
var myObject = {a:1, b:2, c:2};
The old method of counting the number of properties in an object involved looping through the object properties and incrementing a counter:
The new and efficient method of getting the object size involves using the Object.keys()
method:
Isn't it much better? Needless to say, Object.keys()
returns an array of all the properties of an object. Think of its other possible uses.
References#
- MDN - Object.keys()
- MDN - Array.length