Finding an Object's Size in JavaScript
Originally published in the A Drip of JavaScript newsletter.
When working in JavaScript, we inevitably end up using objects as if they were hash/map data structures. While there are new data structures coming, for now we need to just work our way around the hash/map features that JavaScript objects don't have.
One of those little features is a convenient way to tell just how big an object is. Suppose we are doing some analysis of library data and have a set of books and authors that looks like this:
var bookAuthors = {
"Farmer Giles of Ham": "J.R.R. Tolkien",
"Out of the Silent Planet": "C.S. Lewis",
"The Place of the Lion": "Charles Williams",
"Poetic Diction": "Owen Barfield"
};
As part of our analysis, we send the book authors data to an API. Unfortunately, the API will only accept an object with up to a hundred books at a time. So we need a good way to tell how many books are in an object before trying to send them.
Our first inclination might be to try something like this:
function countProperties (obj) {
var count = 0;
for (var property in obj) {
if (Object.prototype.hasOwnProperty.call(obj, property)) {
count++;
}
}
return count;
}
var bookCount = countProperties(bookAuthors);
// Outputs: 4
console.log(bookCount);
While this certainly works, it would be nice to avoid using a hand-rolled method just to count properties. Surely JavaScript has something better available? Fortunately, it does.
While it's not quite as simple as finding the length of an array, it is awfully close. In modern browsers, we can do this:
var bookCount = Object.keys(bookAuthors).length;
// Outputs: 4
console.log(bookCount);
The Object.keys
method returns an array of all the object's own enumerable property keys. And since we are interested in knowing just how many properties there are, we can just check the array's length.
It's a little indirect, but now we can go about our business and make sure that we only call the API when our book count is below the acceptable threshold.
As I mentioned above, the keys
method is only available in modern browsers, and is not available in IE8 and below. If you want to use it in those older browsers you can use es5-shim to make it available.
Thanks for reading!
Josh Clanton