I have a Javascript object that I’m trying to use as a “hashmap”. The keys are always strings, so I don’t think I need anything as sophisticated as what’s described in this SO question. (I also don’t expect the number of keys to go above about 10 so I’m not particularly concerned with lookups being O(n) vs. O(log n) etc.)
The only functionality I want that built-in Javascript objects don’t seem to have, is a quick way to figure out the number of key/value pairs in the object, like what Java’s Map.size returns. Of course, you could just do something like:
function getObjectSize(myObject) {
var count=0
for (var key in myObject)
count++
return count
}
but that seems kind of hacky and roundabout. Is there a “right way” to get the number of fields in the object?
A correction: you need to check
myObject.hasOwnProperty(key)in each iteration, because there’re can be inherited attributes. For example, if you do this before loopObject.prototype.test = 'test',testwill aslo be counted.And talking about your question: you can just define a helper function, if speed doesn’t matter. After all, we define helpers for trim function and other simple things. A lot of javascript is “kind of hacky and roundabout” 🙂
update
Failure example, as requested.
The count returned will be 3.