Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine how many fields a Javascript object has

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?

like image 511
Tyler Avatar asked Jul 01 '10 00:07

Tyler


1 Answers

There is an easier way spec'd in ECMAScript 5.

Object.keys(..) returns an array of all keys defined on the object. Length can be called on that. Try in Chrome:

Object.keys({a: 1, b: 2}).length; // 2

Note that all objects are basically key/value pairs in JavaScript, and they are also very extensible. You could extend the Object.prototype with a size method and get the count there. However, a much better solution is to create a HashMap type interface or use one of the many existing implementations out there, and define size on it. Here's one tiny implementation:

function HashMap() {}

HashMap.prototype.put = function(key, value) {
    this[key] = value;
};

HashMap.prototype.get = function(key) {
    if(typeof this[key] == 'undefined') {
        throw new ReferenceError("key is undefined");
    }
    return this[key];
};

HashMap.prototype.size = function() {
    var count = 0;

    for(var prop in this) {
        // hasOwnProperty check is important because 
        // we don't want to count properties on the prototype chain
        // such as "get", "put", "size", or others.
        if(this.hasOwnProperty(prop) {
            count++;
        }
    }

    return count;
};

Use as (example):

var map = new HashMap();
map.put(someKey, someValue);
map.size();
like image 152
Anurag Avatar answered Nov 07 '22 11:11

Anurag